repo_id
stringclasses 383
values | file_path
stringlengths 7
168
| content
stringlengths 0
1.75M
|
|---|---|---|
amidst
|
src\main\java\amidst\parsing\FormatException.java
|
package amidst.parsing;
@SuppressWarnings("serial")
public class FormatException extends Exception {
public FormatException(String message) {
super(message);
}
public FormatException(Throwable cause) {
super(cause);
}
public FormatException(String message, Throwable cause) {
super(message, cause);
}
}
|
amidst
|
src\main\java\amidst\parsing\URIUtils.java
|
package amidst.parsing;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.util.HashMap;
import amidst.documentation.Immutable;
@Immutable
public enum URIUtils {
;
public static URI newURI(String location) throws IOException {
try {
return URI.create(location);
} catch (IllegalArgumentException e) {
throw new IOException("malformed uri: " + location, e);
}
}
public static URL newURL(String location) throws IOException {
return newURI(location).toURL();
}
public static BufferedReader newReader(String location) throws IOException {
return newReader(newURL(location));
}
public static BufferedReader newReader(URL url) throws IOException {
return new BufferedReader(new InputStreamReader(url.openStream()));
}
public static BufferedInputStream newInputStream(URL url) throws IOException {
return new BufferedInputStream(url.openStream());
}
public static byte[] readBytes(URL url) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
byte buf[] = new byte[4096];
try (InputStream stream = url.openStream()) {
int read;
while((read = stream.read(buf)) >= 0) {
bytes.write(buf, 0, read);
}
}
return bytes.toByteArray();
}
public static FileSystem openZipFile(URI uri) throws URISyntaxException, IOException {
URI zipUri = new URI("jar:" + uri.getScheme(), uri.getPath(), null);
return FileSystems.newFileSystem(zipUri, new HashMap<>());
}
}
|
amidst
|
src\main\java\amidst\settings\ImmutableSetting.java
|
package amidst.settings;
import amidst.documentation.Immutable;
@Immutable
public class ImmutableSetting<T> implements Setting<T> {
private final T value;
public ImmutableSetting(T value) {
this.value = value;
}
@Override
public T get() {
return value;
}
@Override
public void set(T value) {
throw new UnsupportedOperationException("ImmutableSetting cannot be modified!");
}
}
|
amidst
|
src\main\java\amidst\settings\Setting.java
|
package amidst.settings;
import java.util.function.Supplier;
import java.util.prefs.Preferences;
import amidst.documentation.NotNull;
import amidst.mojangapi.world.Dimension;
public interface Setting<T> extends Supplier<T> {
@Override
@NotNull
T get();
void set(@NotNull T value);
public static <T> Setting<T> createImmutable(T value) {
return new ImmutableSetting<>(value);
}
public static Setting<String> createString(Preferences preferences, String key, @NotNull String defaultValue) {
return new SettingBase<>(
defaultValue,
value -> preferences.get(key, value),
value -> preferences.put(key, value));
}
public static Setting<Boolean> createBoolean(Preferences preferences, String key, boolean defaultValue) {
return new SettingBase<>(
defaultValue,
value -> preferences.getBoolean(key, value),
value -> preferences.putBoolean(key, value));
}
public static Setting<Integer> createInteger(Preferences preferences, String key, @NotNull Integer defaultValue) {
return new SettingBase<>(
defaultValue,
value -> preferences.getInt(key, value),
value -> preferences.putInt(key, value));
}
public static Setting<Dimension> createDimension(Preferences preferences, String key, Dimension defaultValue) {
return new SettingBase<>(
defaultValue,
value -> Dimension.fromId(preferences.getInt(key, value.getId())),
value -> preferences.putInt(key, value.getId()));
}
public static <T extends Enum<T>> Setting<T> createEnum(Preferences preferences, String key, T defaultValue) {
Class<T> enumType = defaultValue.getDeclaringClass();
return new SettingBase<>(defaultValue, value -> {
String stored = preferences.get(key, null);
try {
return stored == null ? value : Enum.valueOf(enumType, stored);
} catch (IllegalArgumentException e) {
return value;
}
}, value -> preferences.put(key, value.name()));
}
public static <T> Setting<T> createDummy(T defaultValue) {
return new SettingBase<>(defaultValue, value -> value, value -> {
});
}
@FunctionalInterface
public static interface SettingListener<T> {
public void onSettingChanged(T oldValue, T newValue);
}
public default Setting<T> withListener(SettingListener<T> listener) {
final Setting<T> setting = this;
return new Setting<T>() {
@Override
public T get() {
return setting.get();
}
@Override
public void set(T value) {
T previous = setting.get();
setting.set(value);
listener.onSettingChanged(previous, value);
}
};
}
}
|
amidst
|
src\main\java\amidst\settings\SettingBase.java
|
package amidst.settings;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.UnaryOperator;
import amidst.documentation.ThreadSafe;
@ThreadSafe
public class SettingBase<T> implements Setting<T> {
private final Consumer<T> setter;
private volatile T value;
public SettingBase(T defaultValue, UnaryOperator<T> getter, Consumer<T> setter) {
Objects.requireNonNull(defaultValue);
this.setter = setter;
this.set(getter.apply(defaultValue));
}
@Override
public synchronized T get() {
return value;
}
@Override
public synchronized void set(T value) {
Objects.requireNonNull(value);
this.value = value;
setter.accept(value);
}
}
|
amidst
|
src\main\java\amidst\threading\TaskQueue.java
|
package amidst.threading;
import java.util.concurrent.ConcurrentLinkedQueue;
import amidst.documentation.ThreadSafe;
/**
* This class executes all invoked runnables in the thread that calls
* processTasks.
*/
@ThreadSafe
public class TaskQueue {
private final ConcurrentLinkedQueue<Runnable> tasks = new ConcurrentLinkedQueue<>();
/**
* Executes all tasks. Returns true, if at least one task was executed.
*/
public boolean processTasks() {
boolean result = false;
Runnable task;
while ((task = tasks.poll()) != null) {
result = true;
task.run();
}
return result;
}
public void invoke(Runnable runnable) {
tasks.offer(runnable);
}
}
|
amidst
|
src\main\java\amidst\threading\ThreadMaster.java
|
package amidst.threading;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.ThreadSafe;
@ThreadSafe
public class ThreadMaster {
private static final Runnable NOOP = new Runnable() {
@Override
public void run() {
// noop
}
};
private final ScheduledExecutorService repaintExecutorService;
private final ScheduledExecutorService fragmentLoaderExecutorService;
private final ExecutorService workerExecutorService;
private final WorkerExecutor workerExecutor;
private final CompletableFuture<Thread> fragmentLoaderThread;
private volatile Runnable onRepaintTick;
private volatile Runnable onFragmentLoadTick;
public ThreadMaster() {
this.repaintExecutorService = createRepaintExecutorService();
this.fragmentLoaderExecutorService = createFragmentLoaderExecutorService();
this.workerExecutorService = createWorkerExecutorService();
this.workerExecutor = createWorkerExecutor();
this.fragmentLoaderThread = getFragmentLoader();
this.onRepaintTick = NOOP;
this.onFragmentLoadTick = NOOP;
startRepainter();
startFragmentLoader();
}
private ScheduledExecutorService createRepaintExecutorService() {
return Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
});
}
private ScheduledExecutorService createFragmentLoaderExecutorService() {
return Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
thread.setPriority(Thread.MIN_PRIORITY);
thread.setName("FragmentLoaderExecutor");
return thread;
}
});
}
private ExecutorService createWorkerExecutorService() {
return Executors.newCachedThreadPool(new ThreadFactory() {
int workerNum;
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setPriority(Thread.MIN_PRIORITY);
thread.setName("WorkerExecutor-" + workerNum++);
return thread;
}
});
}
private WorkerExecutor createWorkerExecutor() {
return new WorkerExecutor(workerExecutorService);
}
private void startRepainter() {
repaintExecutorService.scheduleAtFixedRate(new Runnable() {
@CalledOnlyBy(AmidstThread.REPAINTER)
@Override
public void run() {
onRepaintTick.run();
}
}, 0, 20, TimeUnit.MILLISECONDS);
}
private CompletableFuture<Thread> getFragmentLoader() {
return CompletableFuture.supplyAsync(Thread::currentThread, fragmentLoaderExecutorService);
}
private void startFragmentLoader() {
fragmentLoaderExecutorService.scheduleWithFixedDelay(new Runnable() {
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
@Override
public void run() {
onFragmentLoadTick.run();
}
}, 0, 20, TimeUnit.MILLISECONDS);
}
public WorkerExecutor getWorkerExecutor() {
return workerExecutor;
}
public void setOnRepaintTick(Runnable onRepaintTick) {
this.onRepaintTick = onRepaintTick;
}
public void setOnFragmentLoadTick(Runnable onFragmentLoadTick) {
if (fragmentLoaderThread.isDone()) {
LockSupport.unpark(fragmentLoaderThread.join());
}
this.onFragmentLoadTick = onFragmentLoadTick;
}
public void clearOnRepaintTick() {
this.onRepaintTick = NOOP;
}
public void clearOnFragmentLoadTick() {
this.onFragmentLoadTick = NOOP;
}
}
|
amidst
|
src\main\java\amidst\threading\WorkerExecutor.java
|
package amidst.threading;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;
import javax.swing.SwingUtilities;
import amidst.documentation.ThreadSafe;
import amidst.threading.worker.ExceptionalWorker;
import amidst.threading.worker.ExceptionalWorkerWithResult;
import amidst.threading.worker.ProgressReporter;
import amidst.threading.worker.ProgressReportingExceptionalWorker;
import amidst.threading.worker.ProgressReportingExceptionalWorkerWithResult;
import amidst.threading.worker.ProgressReportingWorker;
import amidst.threading.worker.ProgressReportingWorkerWithResult;
import amidst.threading.worker.Worker;
import amidst.threading.worker.WorkerWithResult;
@ThreadSafe
public class WorkerExecutor {
private final ExecutorService executorService;
public WorkerExecutor(ExecutorService executorService) {
this.executorService = executorService;
}
public void run(Worker main) {
runInWorker(() -> {
main.run();
});
}
public void run(ExceptionalWorker main, Consumer<Exception> onException) {
runInWorker(() -> {
try {
main.run();
} catch (Exception e) {
runInEDT(() -> onException.accept(e));
}
});
}
public <P> void run(ProgressReportingWorker<P> main, Consumer<P> onProgress) {
runInWorker(() -> {
main.run(progressReporter(onProgress));
});
}
public <P> void run(
ProgressReportingExceptionalWorker<P> main,
Consumer<P> onProgress,
Consumer<Exception> onException) {
runInWorker(() -> {
try {
main.run(progressReporter(onProgress));
} catch (Exception e) {
runInEDT(() -> onException.accept(e));
}
});
}
public void run(Worker main, Runnable onFinished) {
runInWorker(() -> {
main.run();
runInEDT(() -> onFinished.run());
});
}
public <R> void run(WorkerWithResult<R> main, Consumer<R> onFinished) {
runInWorker(() -> {
R output = main.run();
runInEDT(() -> onFinished.accept(output));
});
}
public void run(ExceptionalWorker main, Runnable onFinished, Consumer<Exception> onException) {
runInWorker(() -> {
try {
main.run();
runInEDT(() -> onFinished.run());
} catch (Exception e) {
runInEDT(() -> onException.accept(e));
}
});
}
public <R> void run(ExceptionalWorkerWithResult<R> main, Consumer<R> onFinished, Consumer<Exception> onException) {
runInWorker(() -> {
try {
R output = main.run();
runInEDT(() -> onFinished.accept(output));
} catch (Exception e) {
runInEDT(() -> onException.accept(e));
}
});
}
public <P> void run(ProgressReportingWorker<P> main, Consumer<P> onProgress, Runnable onFinished) {
runInWorker(() -> {
main.run(progressReporter(onProgress));
runInEDT(() -> onFinished.run());
});
}
public <R, P> void run(
ProgressReportingWorkerWithResult<R, P> main,
Consumer<P> onProgress,
Consumer<R> onFinished) {
runInWorker(() -> {
R output = main.run(progressReporter(onProgress));
runInEDT(() -> onFinished.accept(output));
});
}
public <P> void run(
ProgressReportingExceptionalWorker<P> main,
Consumer<P> onProgress,
Runnable onFinished,
Consumer<Exception> onException) {
runInWorker(() -> {
try {
main.run(progressReporter(onProgress));
runInEDT(() -> onFinished.run());
} catch (Exception e) {
runInEDT(() -> onException.accept(e));
}
});
}
public <R, P> void run(
ProgressReportingExceptionalWorkerWithResult<R, P> main,
Consumer<P> onProgress,
Consumer<R> onFinished,
Consumer<Exception> onException) {
runInWorker(() -> {
try {
R output = main.run(progressReporter(onProgress));
runInEDT(() -> onFinished.accept(output));
} catch (Exception e) {
runInEDT(() -> onException.accept(e));
}
});
}
private <P> ProgressReporter<P> progressReporter(Consumer<P> onProgress) {
return data -> reportProgress(onProgress, data);
}
private <P> void reportProgress(Consumer<P> onProgress, P data) {
runInEDT(() -> onProgress.accept(data));
}
private void runInEDT(Runnable runnable) {
SwingUtilities.invokeLater(runnable);
}
private void runInWorker(Runnable runnable) {
executorService.execute(runnable);
}
}
|
amidst
|
src\main\java\amidst\util\ArrayCache.java
|
package amidst.util;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.ToIntFunction;
import amidst.documentation.ThreadSafe;
@ThreadSafe
public class ArrayCache<A> {
private final ConcurrentLinkedQueue<A> arrays;
private final IntFunction<A> constructor;
private final ToIntFunction<A> lengthGetter;
private final int initialSize;
private ArrayCache(IntFunction<A> constructor, ToIntFunction<A> lengthGetter, int initialSize) {
this.arrays = new ConcurrentLinkedQueue<>();
this.constructor = constructor;
this.lengthGetter = lengthGetter;
this.initialSize = initialSize;
}
public<T, E extends Throwable> T withArrayFaillible(
int minimalSize,
FaillibleFunction<A, T, E> arrayMapper
) throws E {
int requiredSize = Math.max(initialSize, minimalSize);
A dataArray = arrays.poll();
if (dataArray == null) {
// No arrays available in queue: create a fresh one
dataArray = constructor.apply(requiredSize);
} else {
int cur = lengthGetter.applyAsInt(dataArray);
// Array is too small: create a larger one
if (cur < requiredSize) {
do {
cur = Math.max(1, cur*2);
} while (cur < requiredSize);
dataArray = constructor.apply(cur);
}
}
try {
return arrayMapper.apply(dataArray);
} finally {
// We're done with this array, put it back in the queue
arrays.add(dataArray);
}
}
public<T> T withArray(int minimalSize, Function<A, T> arrayMapper) {
return this.withArrayFaillible(minimalSize, (FaillibleFunction<A, T, RuntimeException>) arrayMapper::apply);
}
public static ArrayCache<int[]> makeIntArrayCache(int initialSize) {
return new ArrayCache<>(int[]::new, a -> a.length, initialSize);
}
}
|
amidst
|
src\main\java\amidst\util\ChunkBasedGen.java
|
package amidst.util;
import amidst.mojangapi.minecraftinterface.MinecraftInterfaceException;
import java.util.stream.IntStream;
public enum ChunkBasedGen {
;
/**
* Gets the data for a given area by getting the relevant chunks from a ChunkAccessor.
* <p>
* Use this to implement WorldAccessors which only support getting data from chunk positions,
* rather than block positions.
*/
public static int[] mapChunkBased(int x, int y, int width, int height, boolean useQuarterResolution, ChunkAccessor chunkAccessor) throws MinecraftInterfaceException {
int shift = useQuarterResolution ? 4 : 1;
int blockXBegin = x * shift;
int blockXEnd = (x + width) * shift;
int blockYBegin = y * shift;
int blockYEnd = (y + height) * shift;
int chunkXBegin = (int) Math.floor(blockXBegin / 16.0);
int chunkXEnd = (int) Math.floor(blockXEnd / 16.0);
int chunkZBegin = (int) Math.floor(blockYBegin / 16.0);
int chunkZEnd = (int) Math.floor(blockYEnd / 16.0);
int[][][] biomesByChunk = new int[chunkZEnd - chunkZBegin + 1][][];
for (int chunkZ = chunkZBegin; chunkZ <= chunkZEnd; ++chunkZ) {
biomesByChunk[chunkZ - chunkZBegin] = new int[chunkXEnd - chunkXBegin + 1][];
for (int chunkX = chunkXBegin; chunkX <= chunkXEnd; ++chunkX) {
int[] biomes = chunkAccessor.getChunk(chunkZ, chunkX);
// add to result array
biomesByChunk[chunkZ - chunkZBegin][chunkX - chunkXBegin] = biomes;
}
}
int[] result = new int[width * height];
for (int idxY = 0; idxY < height; ++idxY) {
for (int idxX = 0; idxX < width; ++idxX) {
int blockX = (x + idxX) * shift;
int chunkX = (int) Math.floor(blockX / 16.0);
int blockY = (y + idxY) * shift;
int chunkY = (int) Math.floor(blockY / 16.0);
result[idxX + idxY * width] = biomesByChunk[chunkY - chunkZBegin][chunkX - chunkXBegin][
(blockX - chunkX * 16) + (blockY - chunkY * 16) * 16];
}
}
return result;
}
public static int getIndex(int blockX, int blockY, int blockZ) {
return blockY + blockX * 128 + blockZ * 16 * 128;
}
public static IntStream streamY63() {
return IntStream.range(0, 16)
.flatMap(blockZ -> IntStream.range(0, 16)
.map(blockX -> getIndex(blockZ, 63, blockX)));
}
@FunctionalInterface
public interface ChunkAccessor {
int[] getChunk(int z, int x) throws MinecraftInterfaceException;
}
}
|
amidst
|
src\main\java\amidst\util\FaillibleFunction.java
|
package amidst.util;
@FunctionalInterface
public interface FaillibleFunction<T, U, E extends Throwable> {
public U apply(T value) throws E;
}
|
amidst
|
src\main\java\amidst\util\FastRand.java
|
package amidst.util;
import amidst.documentation.NotThreadSafe;
/**
* Reimplementation of {@code java.util.Random} without the thread safety,
* improving the performance.
*
* See the original implementation <a href="http://hg.openjdk.java.net/jdk10/jdk10/jdk/file/777356696811/src/java.base/share/classes/java/util/Random.java">here</a>
*/
@NotThreadSafe
public class FastRand {
private static final long MULTIPLIER = 0x5DEECE66DL;
private static final long ADDEND = 0xBL;
private static final long MASK = (1L << 48) - 1;
private static final double DOUBLE_UNIT = 0x1.0p-53;
private long seed;
public FastRand(long seed) {
this.seed = initialScramble(seed);
}
private long initialScramble(long seed) {
return (seed ^ MULTIPLIER) & MASK;
}
public void setSeed(long seed) {
this.seed = initialScramble(seed);
}
public void advance() {
seed = (seed * MULTIPLIER + ADDEND) & MASK;
}
private int next(int bits) {
advance();
return (int) (seed >>> 48 - bits);
}
public int nextInt(int bound) {
if (bound <= 0)
throw new IllegalArgumentException("bound must be positive");
int r = next(31);
int m = bound - 1;
if ((bound & m) == 0) { // i.e., bound is a power of 2
r = (int) ((bound * (long) r) >> 31);
} else {
int u = r;
while (u - (r = u % bound) + m < 0) {
u = next(31);
}
}
return r;
}
public long nextLong() {
return ((long) (next(32)) << 32) + next(32);
}
public float nextFloat() {
return next(24) / ((float) (1 << 24));
}
public double nextDouble() {
return (((long) (next(26)) << 27) + next(27)) * DOUBLE_UNIT;
}
}
|
amidst
|
src\main\java\amidst\util\FileExtensionChecker.java
|
package amidst.util;
import amidst.documentation.Immutable;
@Immutable
public enum FileExtensionChecker {
;
/**
* Checks whether the given filename has the given file extension.
*
* @param filename The filename
* @param extension The expected file extension without the leading "."
*/
public static boolean hasFileExtension(String filename, String extension) {
return filename.toLowerCase().endsWith("." + extension);
}
}
|
amidst
|
src\main\java\amidst\util\Lazy.java
|
package amidst.util;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import amidst.documentation.NotNull;
import amidst.documentation.NotThreadSafe;
@NotThreadSafe
public class Lazy<T> {
public static <T> Lazy<T> fromValue(T value) {
Objects.requireNonNull(value, VALUE_NULL_ERROR);
return new Lazy<>(() -> value);
}
public static <T> Lazy<T> from(Supplier<T> supplier) {
Objects.requireNonNull(supplier, SUPPLIER_NULL_ERROR);
return new Lazy<>(supplier);
}
private static final String VALUE_NULL_ERROR = "the value of a lazy cannot be null";
private static final String SUPPLIER_NULL_ERROR = "the supplier of a lazy cannot be null";
private final Supplier<T> supplier;
private T value;
public Lazy(Supplier<T> supplier) {
this.supplier = supplier;
}
@NotNull
public T getOrCreateValue() {
if (value == null) {
value = supplier.get();
Objects.requireNonNull(value, VALUE_NULL_ERROR);
}
return value;
}
public void replaceWithValue(Function<T, T> replacer) {
value = replacer.apply(getOrCreateValue());
}
public void ifInitialized(Consumer<T> consumer) {
if (value != null) {
consumer.accept(value);
}
}
public void setToValue(T value) {
this.value = value;
}
}
|
amidst
|
src\main\java\amidst\util\OperatingSystemDetector.java
|
package amidst.util;
import amidst.documentation.Immutable;
@Immutable
public enum OperatingSystemDetector {
;
private static String OS_NAME = System.getProperty("os.name").toLowerCase();
private static String OS_VERSION = System.getProperty("os.version");
public static boolean isWindows() {
return OS_NAME.indexOf("win") >= 0;
}
public static boolean isMac() {
return OS_NAME.indexOf("mac") >= 0;
}
public static boolean isUnix() {
return OS_NAME.indexOf("nix") >= 0 || OS_NAME.indexOf("nux") >= 0 || OS_NAME.indexOf("aix") > 0;
}
public static boolean isSolaris() {
return OS_NAME.indexOf("sunos") >= 0;
}
public static String getVersion() {
return OS_VERSION;
}
}
|
amidst
|
src\main\java\amidst\util\SwingUtils.java
|
package amidst.util;
import java.awt.Component;
import java.awt.Container;
import java.awt.Window;
import java.lang.reflect.Method;
import java.util.EventListener;
import javax.swing.MenuElement;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.logging.AmidstLogger;
public enum SwingUtils {
;
/**
* This helps with allowing swing components to get garbage collected.
*/
@CalledOnlyBy(AmidstThread.EDT)
public static void destroyComponentTree(Component c) {
// calls the component's dispose method if it has it.
if (c instanceof Window) {
((Window) c).dispose();
}
SwingUtils.removeListeners(c);
if (c instanceof Container) {
for (Component child : ((Container) c).getComponents()) {
destroyComponentTree(child);
}
// for some reason menus don't return their tree correctly when using getComponents, so we have to do this instead
if (c instanceof MenuElement) {
for (MenuElement child : ((MenuElement) c).getSubElements()) {
destroyComponentTree(child.getComponent());
}
}
}
}
/**
* <a href=
* "https://bugs.openjdk.java.net/browse/JDK-4380536?focusedCommentId=12103089&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-12103089">source</a>
*/
@SuppressWarnings("unchecked")
@CalledOnlyBy(AmidstThread.EDT)
public static void removeListeners(Component comp) {
Method[] methods = comp.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
String name = method.getName();
if (name.startsWith("remove") && name.endsWith("Listener")) {
Class<?>[] params = method.getParameterTypes();
if (params.length == 1) {
EventListener[] listeners = null;
try {
listeners = comp.getListeners((Class<? extends EventListener>) params[0]);
} catch (Exception e) {
// It is possible that someone could create a listener
// that doesn't extend from EventListener. If so, ignore it
AmidstLogger.info("Listener " + params[0] + " does not extend EventListener");
continue;
}
for (int j = 0; j < listeners.length; j++) {
try {
method.invoke(comp, new Object[] { listeners[j] });
//AmidstLogger.info("removed Listener " + name + " for comp " + comp + "\n");
} catch (Exception e) {
AmidstLogger.info("Cannot invoke removeListener method " + e);
// Continue on. The reason for removing all listeners is to
// make sure that we don't have a listener holding on to something
// which will keep it from being garbage collected. We want to
// continue freeing listeners to make sure we can free as much
// memory has possible
}
}
} else {
// The only Listener method that I know of that has more than
// one argument is removePropertyChangeListener. If it is
// something other than that, flag it and move on.
if (!name.equals("removePropertyChangeListener"))
AmidstLogger.info(" Wrong number of Args " + name);
}
}
}
}
}
|
amidst
|
src\main\java\amidst\clazz\real\AccessFlags.java
|
package amidst.clazz.real;
import amidst.documentation.Immutable;
/*-
* ACC_PUBLIC 0x0001 Declared public; may be accessed from outside its package.
* ACC_PRIVATE 0x0002 Declared private; usable only within the defining class.
* ACC_PROTECTED 0x0004 Declared protected; may be accessed within subclasses.
* ACC_STATIC 0x0008 Declared static.
* ACC_FINAL 0x0010 Declared final; no further assignment after initialization.
* ACC_VOLATILE 0x0040 Declared volatile; cannot be cached.
* ACC_TRANSIENT 0x0080 Declared transient; not written or read by a persistent object manager.
* ACC_INTERFACE 0x0200 Is an interface, not a class.
**/
@Immutable
public enum AccessFlags {
;
public static final int PUBLIC = 0x01;
public static final int PRIVATE = 0x02;
public static final int PROTECTED = 0x04;
public static final int STATIC = 0x08;
public static final int FINAL = 0x10;
public static final int VOLATILE = 0x40;
public static final int TRANSIENT = 0x80;
public static final int INTERFACE = 0x0200;
public static boolean hasFlags(int accessFlags, int flags) {
return (accessFlags & flags) == flags;
}
}
|
amidst
|
src\main\java\amidst\clazz\real\JarFileParsingException.java
|
package amidst.clazz.real;
import amidst.documentation.Immutable;
@SuppressWarnings("serial")
@Immutable
public class JarFileParsingException extends Exception {
public JarFileParsingException(String message, Throwable cause) {
super(message, cause);
}
}
|
amidst
|
src\main\java\amidst\clazz\real\RealClass.java
|
package amidst.clazz.real;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import amidst.documentation.Immutable;
@Immutable
public class RealClass {
private static Map<Character, String> createPrimitiveTypeConversionMap() {
Map<Character, String> result = new HashMap<>();
result.put('B', "byte");
result.put('C', "char");
result.put('D', "double");
result.put('F', "float");
result.put('I', "int");
result.put('J', "long");
result.put('S', "short");
result.put('Z', "boolean");
result.put('V', "void");
return Collections.unmodifiableMap(result);
}
private static final Map<Character, String> PRIMITIV_TYPE_CONVERSION_MAP = createPrimitiveTypeConversionMap();
private static final Pattern ARG_PATTERN = Pattern.compile("([\\[]+)?([BCDFIJSZV]|L[^;]+)");
private static final Pattern OBJECT_PATTERN = Pattern.compile("^([\\[]+)?[LBCDFIJSZV]");
public static final int CLASS_DATA_WILDCARD = -1;
private final String realClassName;
private final String superClassName;
private final byte[] classData;
private final int minorVersion;
private final int majorVersion;
private final int cpSize;
@SuppressWarnings("unused")
private final int[] constantTypes;
private final RealClassConstant<?>[] constants;
private final List<String> utf8Constants;
private final List<Integer> intConstants;
private final List<Float> floatConstants;
private final List<Double> doubleConstants;
private final List<Long> longConstants;
private final List<Integer> stringIndices;
private final List<ReferenceIndex> methodIndices;
private final int accessFlags;
private final RealClassField[] fields;
private final int numberOfConstructors;
private final int numberOfMethods;
RealClass(
String realClassName,
String superClassName,
byte[] classData,
int minorVersion,
int majorVersion,
int cpSize,
int[] constantTypes,
RealClassConstant<?>[] constants,
List<String> utf8Constants,
List<Integer> intConstants,
List<Float> floatConstants,
List<Double> doubleConstants,
List<Long> longConstants,
List<Integer> stringIndices,
List<ReferenceIndex> methodIndices,
int accessFlags,
RealClassField[] fields,
int numberOfConstructors,
int numberOfMethods) {
this.realClassName = realClassName;
this.superClassName = superClassName;
this.classData = classData;
this.minorVersion = minorVersion;
this.majorVersion = majorVersion;
this.cpSize = cpSize;
this.constantTypes = constantTypes;
this.constants = constants;
this.utf8Constants = utf8Constants;
this.intConstants = intConstants;
this.floatConstants = floatConstants;
this.doubleConstants = doubleConstants;
this.longConstants = longConstants;
this.stringIndices = stringIndices;
this.methodIndices = methodIndices;
this.accessFlags = accessFlags;
this.fields = fields;
this.numberOfConstructors = numberOfConstructors;
this.numberOfMethods = numberOfMethods;
}
public String getRealClassName() {
return realClassName;
}
public String getRealSuperClassName() {
return superClassName;
}
public boolean isClassDataWildcardMatching(int[] bytes) {
int loopLimit = classData.length + 1 - bytes.length;
for (int startIndex = 0; startIndex < loopLimit; startIndex++) {
if (isClassDataWildcardMatchingAt(startIndex, bytes)) {
return true;
}
}
return false;
}
private boolean isClassDataWildcardMatchingAt(int startIndex, int[] bytes) {
for (int offset = 0; offset < bytes.length; offset++) {
if (bytes[offset] != CLASS_DATA_WILDCARD && classData[startIndex + offset] != (byte) bytes[offset]) {
return false;
}
}
return true;
}
public int getMinorVersion() {
return minorVersion;
}
public int getMajorVersion() {
return majorVersion;
}
public int getCpSize() {
return cpSize;
}
public boolean searchForUtf8EqualTo(String required) {
for (String entry : utf8Constants) {
if (entry.equals(required)) {
return true;
}
}
return false;
}
public boolean searchForInt(int required) {
return intConstants.contains(required);
}
public boolean searchForFloat(float required) {
for (Float entry : floatConstants) {
if (entry.floatValue() == required) {
return true;
}
}
return false;
}
public boolean searchForLong(long required) {
for (Long entry : longConstants) {
if (entry.longValue() == required) {
return true;
}
}
return false;
}
public boolean searchForDouble(double required) {
for (Double entry : doubleConstants) {
if (entry.doubleValue() == required) {
return true;
}
}
return false;
}
public boolean searchForStringContaining(String requiredValue) {
for (Integer entry : stringIndices) {
String entryValue = getStringValueOfConstant(entry);
if (entryValue.contains(requiredValue)) {
return true;
}
}
return false;
}
public String searchByReturnType(String required) {
String requiredType = "L" + required + ";";
for (ReferenceIndex entry : methodIndices) {
String value = getStringValueOfConstant(entry.getValue2());
String entryType = value.substring(value.indexOf(')') + 1);
if (entryType.equals(requiredType)) {
return getStringValueOfConstant(entry.getValue1());
}
}
return null;
}
public boolean hasMethodWithRealArgsReturning(String... arguments) {
for (ReferenceIndex entry : methodIndices) {
// Skip constructors
if (!getStringValueOfConstant(entry.getValue1()).equals("<init>")) {
String value = getStringValueOfConstant(entry.getValue2());
String[] args = readArgumentsAndReturn(value);
if (matchSignatureWithRealArgs(args, arguments, true)) {
return true;
}
}
}
return false;
}
public boolean hasConstructorWithRealArgs(String... arguments) {
for (ReferenceIndex entry : methodIndices) {
// Only constructors
if (getStringValueOfConstant(entry.getValue1()).equals("<init>")) {
String value = getStringValueOfConstant(entry.getValue2());
String[] args = readArgumentsAndReturn(value);
if (matchSignatureWithRealArgs(args, arguments, false)) {
return true;
}
}
}
return false;
}
public RealClassField getField(int index) {
return fields[index];
}
public int getAccessFlags() {
return accessFlags;
}
public int getNumberOfConstructors() {
return numberOfConstructors;
}
public int getNumberOfMethods() {
return numberOfMethods;
}
public int getNumberOfFields() {
return fields.length;
}
public boolean isInterface() {
return AccessFlags.hasFlags(accessFlags, AccessFlags.INTERFACE);
}
public boolean isFinal() {
return AccessFlags.hasFlags(accessFlags, AccessFlags.FINAL);
}
private String getStringValueOfConstant(int value) {
return (String) constants[value - 1].getValue();
}
private static boolean matchSignatureWithRealArgs(String[] argsAndReturn, String[] requiredArgs, boolean withReturn) {
int len = withReturn ? argsAndReturn.length : argsAndReturn.length - 1;
if (requiredArgs.length != len) {
return false;
}
for(int i = 0; i < len; i++) {
if (requiredArgs[i] != null && !requiredArgs[i].equals(argsAndReturn[i]))
return false;
}
return true;
}
private String[] readArgumentsAndReturn(String arguments) {
List<String> result = new ArrayList<>();
Matcher matcher = ARG_PATTERN.matcher(arguments);
while (matcher.find()) {
String arg = arguments.substring(matcher.start(), matcher.end());
Matcher objectMatcher = OBJECT_PATTERN.matcher(arg);
if (objectMatcher.find()) {
arg = getObjectArg(arg, objectMatcher.end());
}
result.add(arg);
}
return result.toArray(new String[result.size()]);
}
private String getObjectArg(String arg, int matcherEnd) {
return arg.substring(0, Math.max(0, matcherEnd - 1)) + getPrimitiveType(arg.charAt(matcherEnd - 1))
+ arg.substring(Math.min(matcherEnd, arg.length()));
}
private String getPrimitiveType(char typeChar) {
if (PRIMITIV_TYPE_CONVERSION_MAP.containsKey(typeChar)) {
return PRIMITIV_TYPE_CONVERSION_MAP.get(typeChar);
} else {
return "";
}
}
@Override
public String toString() {
return "[RealClass " + realClassName + "]";
}
}
|
amidst
|
src\main\java\amidst\clazz\real\RealClassBuilder.java
|
package amidst.clazz.real;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import amidst.clazz.real.RealClassConstant.RealClassConstantType;
import amidst.documentation.Immutable;
/**
* See https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.4.8
*/
@Immutable
public class RealClassBuilder {
public RealClass construct(String realClassName, byte[] classData) throws RealClassCreationException {
try (DataInputStream stream = new DataInputStream(new ByteArrayInputStream(classData))) {
return doConstruct(realClassName, classData, stream);
} catch (IOException e) {
throw new RealClassCreationException("unable to create real class for the class: " + realClassName, e);
}
}
private RealClass doConstruct(String realClassName, byte[] classData, DataInputStream stream) throws IOException {
if (isValidClass(stream)) {
int minorVersion = readMinorVersion(stream);
int majorVersion = readMajorVersion(stream);
int cpSize = readCpSize(stream);
int[] constantTypes = new int[cpSize];
RealClassConstant<?>[] constants = new RealClassConstant<?>[cpSize];
List<String> utf8Constants = new ArrayList<>();
List<Integer> intConstants = new ArrayList<>();
List<Float> floatConstants = new ArrayList<>();
List<Double> doubleConstants = new ArrayList<>();
List<Long> longConstants = new ArrayList<>();
List<Integer> stringIndices = new ArrayList<>();
List<ReferenceIndex> methodIndices = new ArrayList<>();
readConstants(
stream,
cpSize,
constantTypes,
constants,
utf8Constants,
intConstants,
floatConstants,
doubleConstants,
longConstants,
stringIndices);
int accessFlags = readAccessFlags(stream);
skipThisClass(stream);
String superClassName = readSuperClass(stream, constants);
skipInterfaces(stream);
RealClassField[] fields = readFields(stream);
int numberOfMethodsAndConstructors = readNumberOfMethodsAndConstructors(stream);
int numberOfConstructors = readMethodsAndConstructors(
stream,
numberOfMethodsAndConstructors,
constants,
methodIndices);
int numberOfMethods = numberOfMethodsAndConstructors - numberOfConstructors;
return new RealClass(
realClassName,
superClassName,
classData,
minorVersion,
majorVersion,
cpSize,
constantTypes,
constants,
utf8Constants,
intConstants,
floatConstants,
doubleConstants,
longConstants,
stringIndices,
methodIndices,
accessFlags,
fields,
numberOfConstructors,
numberOfMethods);
} else {
return null;
}
}
private boolean isValidClass(DataInputStream stream) throws IOException {
return stream.readInt() == 0xCAFEBABE;
}
private int readMinorVersion(DataInputStream stream) throws IOException {
return stream.readUnsignedShort();
}
private int readMajorVersion(DataInputStream stream) throws IOException {
return stream.readUnsignedShort();
}
private int readCpSize(DataInputStream stream) throws IOException {
return stream.readUnsignedShort() - 1;
}
private void readConstants(
DataInputStream stream,
int cpSize,
int[] constantTypes,
RealClassConstant<?>[] constants,
List<String> utf8Constants,
List<Integer> intConstants,
List<Float> floatConstants,
List<Double> doubleConstants,
List<Long> longConstants,
List<Integer> stringIndices) throws IOException {
for (int q = 0; q < cpSize; q++) {
byte type = stream.readByte();
constantTypes[q] = type;
constants[q] = readConstant(stream, type, utf8Constants, intConstants, floatConstants, doubleConstants, longConstants, stringIndices);
if (RealClassConstantType.isQIncreasing(type)) {
q++;
}
}
}
private RealClassConstant<?> readConstant(
DataInputStream stream,
byte type,
List<String> utf8Constants,
List<Integer> intConstants,
List<Float> floatConstants,
List<Double> doubleConstants,
List<Long> longConstants,
List<Integer> stringIndices) throws IOException {
switch (type) {
case RealClassConstantType.STRING:
return readString(stream, type, utf8Constants);
case RealClassConstantType.INTEGER:
return readInteger(stream, type, intConstants);
case RealClassConstantType.FLOAT:
return readFloat(stream, type, floatConstants);
case RealClassConstantType.LONG:
return readLong(stream, type, longConstants);
case RealClassConstantType.DOUBLE:
return readDouble(stream, type, doubleConstants);
case RealClassConstantType.CLASS_REFERENCE:
return readClassReference(stream, type);
case RealClassConstantType.STRING_REFERENCE:
return readStringReference(stream, type, stringIndices);
case RealClassConstantType.FIELD_REFERENCE:
return readAnotherReference(stream, type);
case RealClassConstantType.METHOD_REFERENCE:
return readAnotherReference(stream, type);
case RealClassConstantType.INTERFACE_METHOD_REFERENCE:
return readAnotherReference(stream, type);
case RealClassConstantType.NAME_AND_TYPE_DESCRIPTOR:
return readAnotherReference(stream, type);
case RealClassConstantType.METHOD_HANDLE:
return readMethodHandle(stream, type);
case RealClassConstantType.METHOD_TYPE:
return readMethodType(stream, type);
case RealClassConstantType.INVOKE_DYNAMIC:
return readInvokeDynamic(stream, type);
default:
throw new IOException("unknown constant type: " + type);
}
}
private RealClassConstant<String> readString(DataInputStream stream, byte type, List<String> utf8Constants)
throws IOException {
String value = readStringValue(stream);
utf8Constants.add(value);
return new RealClassConstant<>(type, value);
}
private String readStringValue(DataInputStream stream) throws IOException {
char[] result = new char[stream.readUnsignedShort()];
for (int i = 0; i < result.length; i++) {
result[i] = (char) stream.readByte();
}
return new String(result);
}
private RealClassConstant<Integer> readInteger(DataInputStream stream, byte type, List<Integer> intConstants) throws IOException {
int value = stream.readInt();
intConstants.add(value);
return new RealClassConstant<>(type, value);
}
private RealClassConstant<Float> readFloat(DataInputStream stream, byte type, List<Float> floatConstants)
throws IOException {
float value = stream.readFloat();
floatConstants.add(value);
return new RealClassConstant<>(type, value);
}
private RealClassConstant<Long> readLong(DataInputStream stream, byte type, List<Long> longConstants)
throws IOException {
long value = stream.readLong();
longConstants.add(value);
return new RealClassConstant<>(type, value);
}
private RealClassConstant<Double> readDouble(DataInputStream stream, byte type, List<Double> doubleConstants) throws IOException {
double value = stream.readDouble();
doubleConstants.add(value);
return new RealClassConstant<>(type, value);
}
private RealClassConstant<Integer> readClassReference(DataInputStream stream, byte type) throws IOException {
int value = stream.readUnsignedShort();
return new RealClassConstant<>(type, value);
}
private RealClassConstant<Integer> readStringReference(
DataInputStream stream,
byte type,
List<Integer> stringIndices) throws IOException {
int value = stream.readUnsignedShort();
stringIndices.add(value);
return new RealClassConstant<>(type, value);
}
private RealClassConstant<ReferenceIndex> readAnotherReference(DataInputStream stream, byte type)
throws IOException {
ReferenceIndex value = readReferenceIndex(stream);
return new RealClassConstant<>(type, value);
}
private RealClassConstant<Void> readMethodHandle(DataInputStream stream, byte type) throws IOException {
stream.readByte();
stream.readUnsignedShort();
// return a dummy
return new RealClassConstant<Void>(type, null);
}
private RealClassConstant<Void> readMethodType(DataInputStream stream, byte type) throws IOException {
stream.readUnsignedShort();
// return a dummy
return new RealClassConstant<Void>(type, null);
}
private RealClassConstant<Void> readInvokeDynamic(DataInputStream stream, byte type) throws IOException {
stream.readUnsignedShort();
stream.readUnsignedShort();
// return a dummy
return new RealClassConstant<Void>(type, null);
}
private int readAccessFlags(DataInputStream stream) throws IOException {
return stream.readUnsignedShort();
}
private void skipThisClass(DataInputStream stream) throws IOException {
stream.skip(2);
}
private String readSuperClass(DataInputStream stream, RealClassConstant<?>[] constants) throws IOException {
int superClassEntry = stream.readUnsignedShort();
int superClassName = (Integer) constants[superClassEntry-1].getValue();
return (String) constants[superClassName-1].getValue();
}
private void skipInterfaces(DataInputStream stream) throws IOException {
stream.skip(2 * stream.readUnsignedShort());
}
private RealClassField[] readFields(DataInputStream stream) throws IOException {
RealClassField[] fields = new RealClassField[stream.readUnsignedShort()];
for (int i = 0; i < fields.length; i++) {
fields[i] = new RealClassField(stream.readUnsignedShort());
stream.skip(4);
skipAttributes(stream);
}
return fields;
}
private int readNumberOfMethodsAndConstructors(DataInputStream stream) throws IOException {
return stream.readUnsignedShort();
}
private int readMethodsAndConstructors(
DataInputStream stream,
int numberOfMethodsAndConstructors,
RealClassConstant<?>[] constants,
List<ReferenceIndex> methodIndices) throws IOException {
int numberOfConstructors = 0;
for (int i = 0; i < numberOfMethodsAndConstructors; i++) {
stream.skip(2);
ReferenceIndex referenceIndex = readReferenceIndex(stream);
methodIndices.add(referenceIndex);
String constant = (String) constants[referenceIndex.getValue1() - 1].getValue();
if (constant.contains("<init>")) {
numberOfConstructors++;
}
skipAttributes(stream);
}
return numberOfConstructors;
}
private ReferenceIndex readReferenceIndex(DataInputStream stream) throws IOException {
int value1 = stream.readUnsignedShort();
int value2 = stream.readUnsignedShort();
return new ReferenceIndex(value1, value2);
}
private void skipAttributes(DataInputStream stream) throws IOException {
int attributeInfoCount = stream.readUnsignedShort();
for (int q = 0; q < attributeInfoCount; q++) {
stream.skip(2);
int attributeCount = stream.readInt();
for (int z = 0; z < attributeCount; z++) {
stream.skip(1);
}
}
}
}
|
amidst
|
src\main\java\amidst\clazz\real\RealClassConstant.java
|
package amidst.clazz.real;
import amidst.documentation.Immutable;
@Immutable
public class RealClassConstant<T> {
@Immutable
public static enum RealClassConstantType {
;
public static final int STRING = 1;
public static final int INTEGER = 3;
public static final int FLOAT = 4;
public static final int LONG = 5;
public static final int DOUBLE = 6;
public static final int CLASS_REFERENCE = 7;
public static final int STRING_REFERENCE = 8;
public static final int FIELD_REFERENCE = 9;
public static final int METHOD_REFERENCE = 10;
public static final int INTERFACE_METHOD_REFERENCE = 11;
public static final int NAME_AND_TYPE_DESCRIPTOR = 12;
public static final int METHOD_HANDLE = 15;
public static final int METHOD_TYPE = 16;
public static final int INVOKE_DYNAMIC = 18;
public static boolean isQIncreasing(byte type) {
return type == LONG || type == DOUBLE;
}
}
private final byte type;
private final T value;
public RealClassConstant(byte type, T value) {
this.type = type;
this.value = value;
}
public int getType() {
return type;
}
public T getValue() {
return value;
}
}
|
amidst
|
src\main\java\amidst\clazz\real\RealClassCreationException.java
|
package amidst.clazz.real;
import amidst.documentation.Immutable;
@SuppressWarnings("serial")
@Immutable
public class RealClassCreationException extends Exception {
public RealClassCreationException(String message, Throwable cause) {
super(message, cause);
}
}
|
amidst
|
src\main\java\amidst\clazz\real\RealClassDetector.java
|
package amidst.clazz.real;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiPredicate;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import amidst.documentation.Immutable;
@Immutable
public class RealClassDetector {
private final BiPredicate<RealClass, Map<String, String>> predicate;
public RealClassDetector(BiPredicate<RealClass, Map<String, String>> predicate) {
this.predicate = predicate;
}
public Optional<RealClass> firstMatching(List<RealClass> realClasses, Map<String, String> mappedNames) {
return realClasses.stream().filter(c -> predicate.test(c, mappedNames)).findFirst();
}
public List<RealClass> allMatching(List<RealClass> realClasses, Map<String, String> mappedNames) {
return realClasses.stream().filter(c -> predicate.test(c, mappedNames)).collect(Collectors.toList());
}
}
|
amidst
|
src\main\java\amidst\clazz\real\RealClasses.java
|
package amidst.clazz.real;
import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import amidst.documentation.Immutable;
import amidst.parsing.URIUtils;
@Immutable
public enum RealClasses {
;
private static final int MAXIMUM_CLASS_BYTES = 36 * 1024;
private static final RealClassBuilder REAL_CLASS_BUILDER = new RealClassBuilder();
public static List<RealClass> fromJarFile(Path jarFile) throws FileNotFoundException, JarFileParsingException {
return readRealClassesFromJarFile(jarFile);
}
private static List<RealClass> readRealClassesFromJarFile(Path jarFile)
throws JarFileParsingException,
FileNotFoundException {
if (!Files.exists(jarFile)) {
throw new FileNotFoundException("Attempted to load jar file at: " + jarFile + " but it does not exist.");
}
try (FileSystem jarContents = URIUtils.openZipFile(jarFile.toUri())){
return readJarFile(jarContents);
} catch (IOException | RealClassCreationException | URISyntaxException e) {
throw new JarFileParsingException("Error extracting jar data.", e);
}
}
private static List<RealClass> readJarFile(FileSystem zipFile) throws IOException, RealClassCreationException {
List<RealClass> result = new ArrayList<>();
for (Path root: zipFile.getRootDirectories()) {
readJarFileDirectory(root, result);
}
return result;
}
private static void readJarFileDirectory(Path directory, List<RealClass> result)
throws IOException,
RealClassCreationException {
for (Path path: (Iterable<Path>) Files.list(directory)::iterator) {
String realClassName = getFileNameWithoutExtension(path.getFileName().toString(), "class");
if (Files.isDirectory(path)) {
readJarFileDirectory(path, result);
} else if (realClassName != null) {
RealClass realClass = readRealClass(realClassName, new BufferedInputStream(Files.newInputStream(path)));
if (realClass != null) {
result.add(realClass);
}
}
}
}
private static RealClass readRealClass(String realClassName, BufferedInputStream stream)
throws IOException,
RealClassCreationException {
try (BufferedInputStream theStream = stream) {
// TODO: Double check that this filter won't mess anything up.
if (theStream.available() < MAXIMUM_CLASS_BYTES) {
byte[] classData = new byte[theStream.available()];
theStream.read(classData);
return REAL_CLASS_BUILDER.construct(realClassName, classData);
}
}
return null;
}
private static String getFileNameWithoutExtension(String fileName, String extension) {
String[] split = fileName.split("\\.");
if (split.length == 2 && split[0].indexOf('/') == -1 && split[1].equals(extension)) {
return split[0];
} else {
return null;
}
}
}
|
amidst
|
src\main\java\amidst\clazz\real\RealClassField.java
|
package amidst.clazz.real;
import amidst.documentation.Immutable;
@Immutable
public class RealClassField {
private final int accessFlags;
public RealClassField(int accessFlags) {
this.accessFlags = accessFlags;
}
public boolean hasFlags(int flags) {
return AccessFlags.hasFlags(accessFlags, flags);
}
}
|
amidst
|
src\main\java\amidst\clazz\real\ReferenceIndex.java
|
package amidst.clazz.real;
import amidst.documentation.Immutable;
@Immutable
public class ReferenceIndex {
private final int value1;
private final int value2;
public ReferenceIndex(int value1, int value2) {
this.value1 = value1;
this.value2 = value2;
}
public int getValue1() {
return value1;
}
public int getValue2() {
return value2;
}
}
|
amidst
|
src\main\java\amidst\clazz\symbolic\SymbolicClass.java
|
package amidst.clazz.symbolic;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import amidst.documentation.Immutable;
/**
* The contents of the maps will be altered by the {@link SymbolicClassBuilder}
* after this instance is constructed. However, these maps will not be altered
* after the method {@link SymbolicClassGraphBuilder#construct()} finished
* execution.
*/
@Immutable
public class SymbolicClass {
private final String symbolicClassName;
private final String realClassName;
private final Class<?> clazz;
private final Map<String, SymbolicConstructor> constructorsBySymbolicName;
private final Map<String, SymbolicMethod> methodsBySymbolicName;
private final Map<String, SymbolicField> fieldsBySymbolicName;
public SymbolicClass(
String symbolicClassName,
String realClassName,
Class<?> clazz,
Map<String, SymbolicConstructor> constructorsBySymbolicName,
Map<String, SymbolicMethod> methodsBySymbolicName,
Map<String, SymbolicField> fieldsBySymbolicName) {
this.symbolicClassName = symbolicClassName;
this.realClassName = realClassName;
this.clazz = clazz;
this.constructorsBySymbolicName = constructorsBySymbolicName;
this.methodsBySymbolicName = methodsBySymbolicName;
this.fieldsBySymbolicName = fieldsBySymbolicName;
}
public String getSymbolicName() {
return symbolicClassName;
}
public String getRealName() {
return realClassName;
}
public Class<?> getClazz() {
return clazz;
}
public SymbolicConstructor getConstructor(String symbolicName) {
return constructorsBySymbolicName.get(symbolicName);
}
public SymbolicMethod getMethod(String symbolicName) {
return methodsBySymbolicName.get(symbolicName);
}
public SymbolicField getField(String symbolicName) {
return fieldsBySymbolicName.get(symbolicName);
}
public boolean hasConstructor(String symbolicName) {
return getConstructor(symbolicName) != null;
}
public boolean hasMethod(String symbolicName) {
return getMethod(symbolicName) != null;
}
public boolean hasField(String symbolicName) {
return getField(symbolicName) != null;
}
public SymbolicObject callConstructor(String symbolicName, Object... parameters)
throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException {
return constructorsBySymbolicName.get(symbolicName).call(parameters);
}
public Object callMethod(String symbolicName, SymbolicObject symbolicObject, Object... parameters)
throws IllegalAccessException,
IllegalArgumentException,
InvocationTargetException {
return methodsBySymbolicName.get(symbolicName).call(symbolicObject, parameters);
}
public Object callStaticMethod(String symbolicName, Object... parameters)
throws IllegalAccessException,
IllegalArgumentException,
InvocationTargetException {
return methodsBySymbolicName.get(symbolicName).callStatic(parameters);
}
public Object getFieldValue(String symbolicName, SymbolicObject symbolicObject)
throws IllegalArgumentException,
IllegalAccessException {
return fieldsBySymbolicName.get(symbolicName).getValue(symbolicObject);
}
public Object getStaticFieldValue(String symbolicName) throws IllegalArgumentException, IllegalAccessException {
return fieldsBySymbolicName.get(symbolicName).getStaticValue();
}
@Override
public String toString() {
return realClassName;
}
}
|
amidst
|
src\main\java\amidst\clazz\symbolic\SymbolicClassBuilder.java
|
package amidst.clazz.symbolic;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import amidst.clazz.symbolic.declaration.SymbolicConstructorDeclaration;
import amidst.clazz.symbolic.declaration.SymbolicFieldDeclaration;
import amidst.clazz.symbolic.declaration.SymbolicMethodDeclaration;
import amidst.clazz.symbolic.declaration.SymbolicParameterDeclaration;
import amidst.documentation.NotThreadSafe;
/**
* This class should only be used by the class {@link SymbolicClassGraphBuilder}
*/
@NotThreadSafe
public class SymbolicClassBuilder {
private static Map<String, Class<?>> createPrimitivesMap() {
Map<String, Class<?>> result = new HashMap<>();
result.put("byte", byte.class);
result.put("int", int.class);
result.put("float", float.class);
result.put("short", short.class);
result.put("long", long.class);
result.put("double", double.class);
result.put("boolean", boolean.class);
result.put("char", char.class);
result.put("String", String.class);
return result;
}
private static final Map<String, Class<?>> PRIMITIVES_MAP = createPrimitivesMap();
private final Map<String, SymbolicConstructor> constructorsBySymbolicName = new HashMap<>();
private final Map<String, SymbolicMethod> methodsBySymbolicName = new HashMap<>();
private final Map<String, SymbolicField> fieldsBySymbolicName = new HashMap<>();
private final ClassLoader classLoader;
private final Map<String, String> realClassNamesBySymbolicClassName;
private final Map<String, SymbolicClass> symbolicClassesByRealClassName;
private final SymbolicClass product;
public SymbolicClassBuilder(
ClassLoader classLoader,
Map<String, String> realClassNamesBySymbolicClassName,
Map<String, SymbolicClass> symbolicClassesByRealClassName,
String symbolicClassName,
String realClassName)
throws ClassNotFoundException {
this.classLoader = classLoader;
this.realClassNamesBySymbolicClassName = realClassNamesBySymbolicClassName;
this.symbolicClassesByRealClassName = symbolicClassesByRealClassName;
this.product = new SymbolicClass(
symbolicClassName,
realClassName,
loadClass(realClassName),
constructorsBySymbolicName,
methodsBySymbolicName,
fieldsBySymbolicName);
}
public SymbolicClass getProduct() {
return product;
}
private Class<?> loadClass(String realClassName) throws ClassNotFoundException {
return classLoader.loadClass(realClassName);
}
public void addConstructor(SymbolicConstructorDeclaration declaration) throws SymbolicClassGraphCreationException {
try {
constructorsBySymbolicName.put(declaration.getSymbolicName(), createConstructor(declaration));
} catch (NoSuchMethodException | ClassNotFoundException e) {
declaration.handleMissing(e, product.getSymbolicName(), product.getRealName());
}
}
public void addMethod(SymbolicMethodDeclaration declaration) throws SymbolicClassGraphCreationException {
try {
methodsBySymbolicName.put(declaration.getSymbolicName(), createMethod(declaration));
} catch (NoSuchMethodException | ClassNotFoundException e) {
declaration.handleMissing(e, product.getSymbolicName(), product.getRealName());
}
}
public void addField(SymbolicFieldDeclaration declaration) throws SymbolicClassGraphCreationException {
try {
fieldsBySymbolicName.put(declaration.getSymbolicName(), createField(declaration));
} catch (NoSuchFieldException e) {
declaration.handleMissing(e, product.getSymbolicName(), product.getRealName());
}
}
private SymbolicConstructor createConstructor(SymbolicConstructorDeclaration declaration)
throws ClassNotFoundException,
NoSuchMethodException {
String symbolicName = declaration.getSymbolicName();
Class<?>[] parameterClasses = getParameterClasses(declaration.getParameters().getDeclarations());
Constructor<?> constructor = getConstructor(product.getClazz(), parameterClasses);
return new SymbolicConstructor(product, symbolicName, constructor);
}
private SymbolicMethod createMethod(SymbolicMethodDeclaration declaration)
throws ClassNotFoundException,
NoSuchMethodException {
String symbolicName = declaration.getSymbolicName();
String realName = declaration.getRealName();
Class<?>[] parameterClasses = getParameterClasses(declaration.getParameters().getDeclarations());
Method method = getMethod(product.getClazz(), realName, parameterClasses);
SymbolicClass returnType = getTypeOrSupertype(method.getReturnType());
// We don't want to succeed if the method found is a synthetic method.
if (method.isSynthetic()) {
throw new NoSuchMethodException();
}
return new SymbolicMethod(product, symbolicName, realName, method, returnType);
}
private SymbolicField createField(SymbolicFieldDeclaration declaration) throws NoSuchFieldException {
String symbolicName = declaration.getSymbolicName();
String realName = declaration.getRealName();
Field field = getField(product.getClazz(), realName);
SymbolicClass type = getTypeOrSupertype(field.getType());
return new SymbolicField(product, symbolicName, realName, field, type);
}
private Constructor<?> getConstructor(Class<?> clazz, Class<?>[] parameterClasses) throws NoSuchMethodException {
Constructor<?> result = clazz.getConstructor(parameterClasses);
result.setAccessible(true);
return result;
}
private Method getMethod(Class<?> clazz, String realName, Class<?>[] parameterClasses)
throws NoSuchMethodException {
Method result = clazz.getDeclaredMethod(realName, parameterClasses);
result.setAccessible(true);
return result;
}
private Field getField(Class<?> clazz, String realName) throws NoSuchFieldException {
Field result = clazz.getDeclaredField(realName);
result.setAccessible(true);
return result;
}
private Class<?>[] getParameterClasses(List<SymbolicParameterDeclaration> declarations)
throws ClassNotFoundException {
Class<?>[] result = new Class<?>[declarations.size()];
for (int i = 0; i < declarations.size(); i++) {
SymbolicParameterDeclaration declaration = declarations.get(i);
result[i] = getArrayClass(getParameterClass(declaration), declaration.getArrayDimensions());
}
return result;
}
private Class<?> getParameterClass(SymbolicParameterDeclaration declaration) throws ClassNotFoundException {
Class<?> result = PRIMITIVES_MAP.get(declaration.getType());
if (result != null) {
return result;
} else if (declaration.isSymbolic()) {
String realClassName = realClassNamesBySymbolicClassName.get(declaration.getType());
if (realClassName != null) {
return classLoader.loadClass(realClassName);
} else {
throw new ClassNotFoundException("cannot resolve symbolic class name: " + declaration.getType());
}
} else {
return classLoader.loadClass(declaration.getType());
}
}
public static Class<?> getArrayClass(Class<?> elementType, int dimensions) {
return dimensions == 0 ? elementType : Array.newInstance(elementType, new int[dimensions]).getClass();
}
private SymbolicClass getType(Class<?> type) {
String result = type.getName();
if (result.contains(".")) {
String[] typeSplit = result.split("\\.");
result = typeSplit[typeSplit.length - 1];
}
return symbolicClassesByRealClassName.get(result);
}
private SymbolicClass getTypeOrSupertype(Class<?> type) {
// Check the class hierarchy of 'type' to find a known class
Class<?> clazz = type;
while (clazz != null) {
SymbolicClass symClass = getType(clazz);
if (symClass != null) {
return symClass;
}
clazz = clazz.getSuperclass();
}
return null;
}
}
|
amidst
|
src\main\java\amidst\clazz\symbolic\SymbolicClasses.java
|
package amidst.clazz.symbolic;
import java.util.Map;
import amidst.clazz.symbolic.declaration.SymbolicClassDeclaration;
import amidst.documentation.Immutable;
@Immutable
public enum SymbolicClasses {
;
public static Map<String, SymbolicClass> from(
Map<SymbolicClassDeclaration, String> realClassNamesBySymbolicClassDeclaration,
ClassLoader classLoader) throws SymbolicClassGraphCreationException {
return new SymbolicClassGraphBuilder(classLoader, realClassNamesBySymbolicClassDeclaration).construct();
}
}
|
amidst
|
src\main\java\amidst\clazz\symbolic\SymbolicClassGraphBuilder.java
|
package amidst.clazz.symbolic;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import amidst.clazz.symbolic.declaration.SymbolicClassDeclaration;
import amidst.clazz.symbolic.declaration.SymbolicConstructorDeclaration;
import amidst.clazz.symbolic.declaration.SymbolicFieldDeclaration;
import amidst.clazz.symbolic.declaration.SymbolicMethodDeclaration;
import amidst.documentation.Immutable;
@Immutable
public class SymbolicClassGraphBuilder {
private final ClassLoader classLoader;
private final Map<SymbolicClassDeclaration, String> realClassNamesBySymbolicClassDeclaration;
public SymbolicClassGraphBuilder(
ClassLoader classLoader,
Map<SymbolicClassDeclaration, String> realClassNamesBySymbolicClassDeclaration) {
this.classLoader = classLoader;
this.realClassNamesBySymbolicClassDeclaration = realClassNamesBySymbolicClassDeclaration;
}
public Map<String, SymbolicClass> construct() throws SymbolicClassGraphCreationException {
Map<String, String> realClassNamesBySymbolicClassName = new HashMap<>();
Map<String, SymbolicClass> symbolicClassesByRealClassName = new HashMap<>();
Map<SymbolicClassDeclaration, SymbolicClassBuilder> symbolicClassBuildersBySymbolicClassDeclaration = new HashMap<>();
createSymbolicClasses(
realClassNamesBySymbolicClassName,
symbolicClassesByRealClassName,
symbolicClassBuildersBySymbolicClassDeclaration);
addConstructorsMethodsAndFields(symbolicClassBuildersBySymbolicClassDeclaration);
return createProduct(symbolicClassBuildersBySymbolicClassDeclaration);
}
private void createSymbolicClasses(
Map<String, String> realClassNamesBySymbolicClassName,
Map<String, SymbolicClass> symbolicClassesByRealClassName,
Map<SymbolicClassDeclaration, SymbolicClassBuilder> symbolicClassBuildersBySymbolicClassDeclaration)
throws SymbolicClassGraphCreationException {
for (Entry<SymbolicClassDeclaration, String> entry : realClassNamesBySymbolicClassDeclaration.entrySet()) {
SymbolicClassDeclaration declaration = entry.getKey();
String symbolicClassName = declaration.getSymbolicClassName();
String realClassName = entry.getValue();
try {
SymbolicClassBuilder builder = new SymbolicClassBuilder(
classLoader,
realClassNamesBySymbolicClassName,
symbolicClassesByRealClassName,
declaration.getSymbolicClassName(),
realClassName);
SymbolicClass symbolicClass = builder.getProduct();
realClassNamesBySymbolicClassName.put(symbolicClassName, realClassName);
symbolicClassesByRealClassName.put(realClassName, symbolicClass);
symbolicClassBuildersBySymbolicClassDeclaration.put(declaration, builder);
} catch (ClassNotFoundException e) {
declaration.handleMissing(e, realClassName);
}
}
}
private void addConstructorsMethodsAndFields(
Map<SymbolicClassDeclaration, SymbolicClassBuilder> symbolicClassBuildersBySymbolicClassDeclaration)
throws SymbolicClassGraphCreationException {
for (Entry<SymbolicClassDeclaration, SymbolicClassBuilder> entry : symbolicClassBuildersBySymbolicClassDeclaration
.entrySet()) {
SymbolicClassDeclaration declaration = entry.getKey();
SymbolicClassBuilder builder = entry.getValue();
addConstructors(builder, declaration.getConstructors());
addMethods(builder, declaration.getMethods());
addFields(builder, declaration.getFields());
}
}
private void addConstructors(SymbolicClassBuilder builder, List<SymbolicConstructorDeclaration> constructors)
throws SymbolicClassGraphCreationException {
for (SymbolicConstructorDeclaration constructor : constructors) {
builder.addConstructor(constructor);
}
}
private void addMethods(SymbolicClassBuilder builder, List<SymbolicMethodDeclaration> methods)
throws SymbolicClassGraphCreationException {
for (SymbolicMethodDeclaration method : methods) {
builder.addMethod(method);
}
}
private void addFields(SymbolicClassBuilder builder, List<SymbolicFieldDeclaration> fields)
throws SymbolicClassGraphCreationException {
for (SymbolicFieldDeclaration field : fields) {
builder.addField(field);
}
}
private Map<String, SymbolicClass> createProduct(
Map<SymbolicClassDeclaration, SymbolicClassBuilder> symbolicClassBuildersBySymbolicClassDeclaration) {
Map<String, SymbolicClass> result = new HashMap<>();
for (Entry<SymbolicClassDeclaration, SymbolicClassBuilder> entry : symbolicClassBuildersBySymbolicClassDeclaration
.entrySet()) {
result.put(entry.getKey().getSymbolicClassName(), entry.getValue().getProduct());
}
return result;
}
}
|
amidst
|
src\main\java\amidst\clazz\symbolic\SymbolicClassGraphCreationException.java
|
package amidst.clazz.symbolic;
import amidst.documentation.Immutable;
@Immutable
@SuppressWarnings("serial")
public class SymbolicClassGraphCreationException extends Exception {
public SymbolicClassGraphCreationException(String message, Throwable cause) {
super(message, cause);
}
}
|
amidst
|
src\main\java\amidst\clazz\symbolic\SymbolicConstructor.java
|
package amidst.clazz.symbolic;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import amidst.documentation.Immutable;
@Immutable
public class SymbolicConstructor {
private final SymbolicClass parent;
private final String symbolicName;
private final Constructor<?> constructor;
public SymbolicConstructor(SymbolicClass parent, String symbolicName, Constructor<?> constructor) {
this.parent = parent;
this.symbolicName = symbolicName;
this.constructor = constructor;
}
public SymbolicObject call(Object... parameters)
throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException {
return new SymbolicObject(parent, newInstance(parameters));
}
public Constructor<?> getRawConstructor() {
return constructor;
}
private Object newInstance(Object... parameters)
throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException {
return constructor.newInstance(parameters);
}
@Override
public String toString() {
return "[Constructor " + symbolicName + " of class " + parent.getSymbolicName() + "]";
}
}
|
amidst
|
src\main\java\amidst\clazz\symbolic\SymbolicField.java
|
package amidst.clazz.symbolic;
import java.lang.reflect.Field;
import amidst.documentation.Immutable;
@Immutable
public class SymbolicField {
private final SymbolicClass parent;
private final String symbolicName;
private final String realName;
private final Field field;
private final SymbolicClass type;
public SymbolicField(SymbolicClass parent, String symbolicName, String realName, Field field, SymbolicClass type) {
this.parent = parent;
this.symbolicName = symbolicName;
this.realName = realName;
this.field = field;
this.type = type;
}
public Field getRawField() {
return field;
}
public Object getValue(SymbolicObject symbolicObject) throws IllegalArgumentException, IllegalAccessException {
return getValueFromObject(symbolicObject.getObject());
}
public Object getStaticValue() throws IllegalArgumentException, IllegalAccessException {
return getValueFromObject(null);
}
private Object getValueFromObject(Object object) throws IllegalArgumentException, IllegalAccessException {
Object value = get(object);
if (isTypeSymbolicClass()) {
return new SymbolicObject(type, value);
} else {
return value;
}
}
private Object get(Object object) throws IllegalArgumentException, IllegalAccessException {
return field.get(object);
}
private boolean isTypeSymbolicClass() {
return type != null;
}
@Override
public String toString() {
return "[Field " + symbolicName + " (" + realName + ") of class " + parent.getSymbolicName() + "]";
}
}
|
amidst
|
src\main\java\amidst\clazz\symbolic\SymbolicMethod.java
|
package amidst.clazz.symbolic;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import amidst.documentation.Immutable;
@Immutable
public class SymbolicMethod {
private final SymbolicClass parent;
private final String symbolicName;
private final String realName;
private final Method method;
private final SymbolicClass returnType;
public SymbolicMethod(
SymbolicClass parent,
String symbolicName,
String realName,
Method method,
SymbolicClass returnType) {
this.parent = parent;
this.symbolicName = symbolicName;
this.realName = realName;
this.method = method;
this.returnType = returnType;
}
public String getSymbolicName() {
return symbolicName;
}
public String getRealName() {
return realName;
}
public Method getRawMethod() {
return method;
}
public boolean hasModifiers(int modifiers) {
return (method.getModifiers() & modifiers) != 0;
}
public boolean hasReturnType(Class<?> type) {
return type.equals(method.getReturnType());
}
public Object call(SymbolicObject symbolicObject, Object... parameters)
throws IllegalAccessException,
IllegalArgumentException,
InvocationTargetException {
return callFromObject(symbolicObject.getObject(), parameters);
}
public Object callStatic(Object... parameters)
throws IllegalAccessException,
IllegalArgumentException,
InvocationTargetException {
return callFromObject(null, parameters);
}
private Object callFromObject(Object object, Object... parameters)
throws IllegalAccessException,
IllegalArgumentException,
InvocationTargetException {
Object value = invoke(object, parameters);
if (isReturnTypeSymbolicClass()) {
return new SymbolicObject(returnType, value);
}
return value;
}
private Object invoke(Object object, Object... parameters)
throws IllegalAccessException,
IllegalArgumentException,
InvocationTargetException {
return method.invoke(object, parameters);
}
private boolean isReturnTypeSymbolicClass() {
return returnType != null;
}
@Override
public String toString() {
return "[Method " + symbolicName + " (" + realName + ") of class " + parent.getSymbolicName() + "]";
}
}
|
amidst
|
src\main\java\amidst\clazz\symbolic\SymbolicObject.java
|
package amidst.clazz.symbolic;
import java.lang.reflect.InvocationTargetException;
import amidst.documentation.Immutable;
/**
* While the state that is directly contained in instances of this class cannot
* be altered, it is still possible to alter the object that is contained in it.
*/
@Immutable
public class SymbolicObject {
private final SymbolicClass type;
private final Object object;
public SymbolicObject(SymbolicClass type, Object object) {
this.type = type;
this.object = object;
}
public SymbolicClass getType() {
return type;
}
public Object getObject() {
return object;
}
public boolean hasMethod(String symbolicName) {
return type.hasMethod(symbolicName);
}
public boolean hasField(String symbolicName) {
return type.hasField(symbolicName);
}
public Object callMethod(String symbolicName, Object... parameters)
throws IllegalAccessException,
IllegalArgumentException,
InvocationTargetException {
return type.callMethod(symbolicName, this, parameters);
}
public Object getFieldValue(String symbolicName) throws IllegalArgumentException, IllegalAccessException {
return type.getFieldValue(symbolicName, this);
}
}
|
amidst
|
src\main\java\amidst\clazz\translator\ClassTranslator.java
|
package amidst.clazz.translator;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import amidst.clazz.real.RealClass;
import amidst.clazz.real.RealClassDetector;
import amidst.clazz.symbolic.declaration.SymbolicClassDeclaration;
import amidst.documentation.Immutable;
@Immutable
public class ClassTranslator {
public static CTBuilder builder() {
return CTBuilder.newInstance();
}
private final List<Map.Entry<RealClassDetector, SymbolicClassDeclaration>> translations;
public ClassTranslator(List<Map.Entry<RealClassDetector, SymbolicClassDeclaration>> translations) {
this.translations = translations;
}
public Map<SymbolicClassDeclaration, List<RealClass>> translateToAllMatching(List<RealClass> realClasses) {
Map<SymbolicClassDeclaration, List<RealClass>> result = new HashMap<>();
Map<String, String> foundNames = new HashMap<>();
Map<String, String> foundNamesView = Collections.unmodifiableMap(foundNames);
for (Entry<RealClassDetector, SymbolicClassDeclaration> entry : translations) {
SymbolicClassDeclaration declaration = entry.getValue();
List<RealClass> allMatching = entry.getKey().allMatching(realClasses, foundNamesView);
if (result.containsKey(declaration)) {
result.get(declaration).addAll(allMatching);
} else {
result.put(declaration, allMatching);
allMatching.stream()
.findFirst()
.ifPresent(c -> foundNames.put(declaration.getSymbolicClassName(), c.getRealClassName()));
}
}
return result;
}
public Map<SymbolicClassDeclaration, String> translate(List<RealClass> realClasses) throws ClassNotFoundException {
Map<SymbolicClassDeclaration, String> result = new HashMap<>();
Map<String, String> foundNames = new HashMap<>();
Map<String, String> foundNamesView = Collections.unmodifiableMap(foundNames);
for (Entry<RealClassDetector, SymbolicClassDeclaration> entry : translations) {
Optional<String> realClassName = entry.getKey().firstMatching(realClasses, foundNamesView).map(RealClass::getRealClassName);
SymbolicClassDeclaration declaration = entry.getValue();
realClassName.ifPresent(name -> foundNames.put(declaration.getSymbolicClassName(), name));
addResult(
result,
declaration,
realClassName);
}
return result;
}
private void addResult(
Map<SymbolicClassDeclaration, String> result,
SymbolicClassDeclaration declaration,
Optional<String> realClassName) throws ClassNotFoundException {
if (!realClassName.isPresent()) {
declaration.handleNoMatch();
} else if (result.containsKey(declaration)) {
declaration.handleMultipleMatches(result.get(declaration), realClassName.get());
} else {
declaration.handleMatch(realClassName.get());
result.put(declaration, realClassName.get());
}
}
}
|
amidst
|
src\main\java\amidst\clazz\translator\CTBuilder.java
|
package amidst.clazz.translator;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiPredicate;
import java.util.function.Predicate;
import amidst.clazz.real.RealClass;
import amidst.clazz.real.RealClassDetector;
import amidst.clazz.symbolic.declaration.SymbolicClassDeclaration;
import amidst.clazz.symbolic.declaration.SymbolicConstructorDeclaration;
import amidst.clazz.symbolic.declaration.SymbolicFieldDeclaration;
import amidst.clazz.symbolic.declaration.SymbolicMethodDeclaration;
import amidst.clazz.symbolic.declaration.SymbolicParameterDeclarationList;
import amidst.clazz.symbolic.declaration.SymbolicParameterDeclarationList.ExecuteOnEnd;
import amidst.clazz.symbolic.declaration.SymbolicParameterDeclarationList.SymbolicParameterDeclarationListBuilder;
import amidst.documentation.NotThreadSafe;
/**
* While this class is not thread-safe by itself, its product is thread-safe.
*/
@NotThreadSafe
public class CTBuilder {
@NotThreadSafe
public class SCDBuilder {
private String symbolicClassName;
private boolean isOptional;
private final List<SymbolicConstructorDeclaration> constructors = new ArrayList<>();
private final List<SymbolicMethodDeclaration> methods = new ArrayList<>();
private final List<SymbolicFieldDeclaration> fields = new ArrayList<>();
private void init(String symbolicClassName, boolean isOptional) {
this.symbolicClassName = symbolicClassName;
this.isOptional = isOptional;
}
private SymbolicClassDeclaration constructThis() {
return new SymbolicClassDeclaration(symbolicClassName, isOptional, constructors, methods, fields);
}
public CTBuilder next() {
return new CTBuilder(CTBuilder.this);
}
public ClassTranslator construct() {
return CTBuilder.this.construct();
}
public SymbolicParameterDeclarationListBuilder<SCDBuilder> requiredConstructor(final String symbolicName) {
return constructor(symbolicName, false);
}
public SymbolicParameterDeclarationListBuilder<SCDBuilder> optionalConstructor(final String symbolicName) {
return constructor(symbolicName, true);
}
private SymbolicParameterDeclarationListBuilder<SCDBuilder> constructor(
final String symbolicName,
final boolean isOptional) {
return new SymbolicParameterDeclarationListBuilder<>(this, new ExecuteOnEnd() {
@Override
public void run(SymbolicParameterDeclarationList parameters) {
constructors.add(new SymbolicConstructorDeclaration(symbolicName, isOptional, parameters));
}
});
}
public SymbolicParameterDeclarationListBuilder<SCDBuilder> requiredMethod(
String symbolicName,
String realName) {
return method(symbolicName, realName, false);
}
public SymbolicParameterDeclarationListBuilder<SCDBuilder> optionalMethod(
String symbolicName,
String realName) {
return method(symbolicName, realName, true);
}
private SymbolicParameterDeclarationListBuilder<SCDBuilder> method(
final String symbolicName,
final String realName,
final boolean isOptional) {
return new SymbolicParameterDeclarationListBuilder<>(this, new ExecuteOnEnd() {
@Override
public void run(SymbolicParameterDeclarationList parameters) {
methods.add(new SymbolicMethodDeclaration(symbolicName, realName, isOptional, parameters));
}
});
}
public SCDBuilder requiredField(String symbolicName, String realName) {
return field(symbolicName, realName, false);
}
public SCDBuilder optionalField(String symbolicName, String realName) {
return field(symbolicName, realName, true);
}
private SCDBuilder field(String symbolicName, String realName, boolean isOptional) {
fields.add(new SymbolicFieldDeclaration(symbolicName, realName, isOptional));
return this;
}
}
public static CTBuilder newInstance() {
return new CTBuilder(null);
}
private final CTBuilder previous;
private RealClassDetector detector = null;
private final SCDBuilder declarationBuilder = new SCDBuilder();
private CTBuilder(CTBuilder previous) {
this.previous = previous;
}
public CTBuilder ifDetect(Predicate<RealClass> predicate) {
return ifDetect((c, m) -> predicate.test(c));
}
public CTBuilder ifDetect(BiPredicate<RealClass, Map<String, String>> biPredicate) {
this.detector = new RealClassDetector(biPredicate);
return this;
}
public SCDBuilder thenDeclareRequired(String symbolicClassName) {
return thenDeclare(symbolicClassName, false);
}
public SCDBuilder thenDeclareOptional(String symbolicClassName) {
return thenDeclare(symbolicClassName, true);
}
private SCDBuilder thenDeclare(String symbolicClassName, boolean isOptional) {
if (detector == null) {
throw new IllegalStateException("can't declare a symbolic class without calling ifDetect before");
}
declarationBuilder.init(symbolicClassName, isOptional);
return declarationBuilder;
}
public ClassTranslator construct() {
return new ClassTranslator(constructResult());
}
private List<Map.Entry<RealClassDetector, SymbolicClassDeclaration>> constructResult() {
List<Map.Entry<RealClassDetector, SymbolicClassDeclaration>> result = constructPreviousResult();
result.add(new AbstractMap.SimpleImmutableEntry<>(detector, declarationBuilder.constructThis()));
return result;
}
private List<Map.Entry<RealClassDetector, SymbolicClassDeclaration>> constructPreviousResult() {
if (previous != null) {
return previous.constructResult();
} else {
return new ArrayList<>();
}
}
}
|
amidst
|
src\main\java\amidst\clazz\symbolic\declaration\SymbolicClassDeclaration.java
|
package amidst.clazz.symbolic.declaration;
import java.util.Collections;
import java.util.List;
import amidst.clazz.symbolic.SymbolicClassGraphCreationException;
import amidst.documentation.Immutable;
import amidst.logging.AmidstLogger;
@Immutable
public class SymbolicClassDeclaration {
private final String symbolicClassName;
private final boolean isOptional;
private final List<SymbolicConstructorDeclaration> constructors;
private final List<SymbolicMethodDeclaration> methods;
private final List<SymbolicFieldDeclaration> fields;
public SymbolicClassDeclaration(
String symbolicClassName,
boolean isOptional,
List<SymbolicConstructorDeclaration> constructors,
List<SymbolicMethodDeclaration> methods,
List<SymbolicFieldDeclaration> fields) {
this.symbolicClassName = symbolicClassName;
this.isOptional = isOptional;
this.constructors = Collections.unmodifiableList(constructors);
this.methods = Collections.unmodifiableList(methods);
this.fields = Collections.unmodifiableList(fields);
}
public String getSymbolicClassName() {
return symbolicClassName;
}
public boolean isOptional() {
return isOptional;
}
public List<SymbolicConstructorDeclaration> getConstructors() {
return constructors;
}
public List<SymbolicMethodDeclaration> getMethods() {
return methods;
}
public List<SymbolicFieldDeclaration> getFields() {
return fields;
}
public void handleMultipleMatches(String firstRealClassName, String otherRealClassName) {
AmidstLogger
.warn("Found class {} again: {}, {}", symbolicClassName, firstRealClassName, otherRealClassName);
}
public void handleMatch(String realClassName) {
AmidstLogger.info("Found class {}: {}", symbolicClassName, realClassName);
}
public void handleNoMatch() throws ClassNotFoundException {
if (isOptional) {
AmidstLogger.info("Missing class {}", symbolicClassName);
} else {
throw new ClassNotFoundException(
"cannot find a real class matching the symbolic class " + symbolicClassName);
}
}
public void handleMissing(ClassNotFoundException e, String realClassName)
throws SymbolicClassGraphCreationException {
String message = "unable to find the real class " + realClassName + " -> " + symbolicClassName;
if (isOptional) {
AmidstLogger.info(message);
} else {
throw new SymbolicClassGraphCreationException(message, e);
}
}
}
|
amidst
|
src\main\java\amidst\clazz\symbolic\declaration\SymbolicConstructorDeclaration.java
|
package amidst.clazz.symbolic.declaration;
import amidst.clazz.symbolic.SymbolicClassGraphCreationException;
import amidst.documentation.Immutable;
import amidst.logging.AmidstLogger;
@Immutable
public class SymbolicConstructorDeclaration {
private final String symbolicName;
private final boolean isOptional;
private final SymbolicParameterDeclarationList parameters;
public SymbolicConstructorDeclaration(
String symbolicName,
boolean isOptional,
SymbolicParameterDeclarationList parameters) {
this.symbolicName = symbolicName;
this.isOptional = isOptional;
this.parameters = parameters;
}
public String getSymbolicName() {
return symbolicName;
}
public boolean isOptional() {
return isOptional;
}
public SymbolicParameterDeclarationList getParameters() {
return parameters;
}
public void handleMissing(Exception e, String symbolicClassName, String realClassName)
throws SymbolicClassGraphCreationException {
String message = "unable to find the real class constructor " + realClassName + ".<init>"
+ parameters.getParameterString() + " -> " + symbolicClassName + "." + symbolicName;
if (isOptional) {
AmidstLogger.info(message);
} else {
throw new SymbolicClassGraphCreationException(message, e);
}
}
}
|
amidst
|
src\main\java\amidst\clazz\symbolic\declaration\SymbolicFieldDeclaration.java
|
package amidst.clazz.symbolic.declaration;
import amidst.clazz.symbolic.SymbolicClassGraphCreationException;
import amidst.documentation.Immutable;
import amidst.logging.AmidstLogger;
@Immutable
public class SymbolicFieldDeclaration {
private final String symbolicName;
private final String realName;
private final boolean isOptional;
public SymbolicFieldDeclaration(String symbolicName, String realName, boolean isOptional) {
this.symbolicName = symbolicName;
this.realName = realName;
this.isOptional = isOptional;
}
public String getSymbolicName() {
return symbolicName;
}
public String getRealName() {
return realName;
}
public boolean isOptional() {
return isOptional;
}
public void handleMissing(Exception e, String symbolicClassName, String realClassName)
throws SymbolicClassGraphCreationException {
String message = "unable to find the real class field " + realClassName + "." + realName + " -> "
+ symbolicClassName + "." + symbolicName;
if (isOptional) {
AmidstLogger.info(message);
} else {
throw new SymbolicClassGraphCreationException(message, e);
}
}
}
|
amidst
|
src\main\java\amidst\clazz\symbolic\declaration\SymbolicMethodDeclaration.java
|
package amidst.clazz.symbolic.declaration;
import amidst.clazz.symbolic.SymbolicClassGraphCreationException;
import amidst.documentation.Immutable;
import amidst.logging.AmidstLogger;
@Immutable
public class SymbolicMethodDeclaration {
private final String symbolicName;
private final String realName;
private final boolean isOptional;
private final SymbolicParameterDeclarationList parameters;
public SymbolicMethodDeclaration(
String symbolicName,
String realName,
boolean isOptional,
SymbolicParameterDeclarationList parameters) {
this.symbolicName = symbolicName;
this.realName = realName;
this.isOptional = isOptional;
this.parameters = parameters;
}
public String getSymbolicName() {
return symbolicName;
}
public String getRealName() {
return realName;
}
public boolean isOptional() {
return isOptional;
}
public SymbolicParameterDeclarationList getParameters() {
return parameters;
}
public void handleMissing(Exception e, String symbolicClassName, String realClassName)
throws SymbolicClassGraphCreationException {
String message = "unable to find the real class method " + realClassName + "." + realName
+ parameters.getParameterString() + " -> " + symbolicClassName + "." + symbolicName;
if (isOptional) {
AmidstLogger.info(message);
} else {
throw new SymbolicClassGraphCreationException(message, e);
}
}
}
|
amidst
|
src\main\java\amidst\clazz\symbolic\declaration\SymbolicParameterDeclaration.java
|
package amidst.clazz.symbolic.declaration;
import amidst.documentation.Immutable;
@Immutable
public class SymbolicParameterDeclaration {
private final String type;
private final boolean isSymbolic;
private final int arrayDimensions;
public SymbolicParameterDeclaration(String type, boolean isSymbolic) {
this.type = type;
this.isSymbolic = isSymbolic;
this.arrayDimensions = 0;
}
public SymbolicParameterDeclaration(String type, boolean isSymbolic, int arrayDimensions) {
this.type = type;
this.isSymbolic = isSymbolic;
this.arrayDimensions = arrayDimensions;
}
public String getType() {
return type;
}
public boolean isSymbolic() {
return isSymbolic;
}
public int getArrayDimensions() {
return arrayDimensions;
}
public String getParameterString() {
if (isSymbolic) {
return "@" + type;
} else {
return type;
}
}
}
|
amidst
|
src\main\java\amidst\clazz\symbolic\declaration\SymbolicParameterDeclarationList.java
|
package amidst.clazz.symbolic.declaration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import amidst.documentation.Immutable;
@Immutable
public class SymbolicParameterDeclarationList {
public static interface ExecuteOnEnd {
public void run(SymbolicParameterDeclarationList parameters);
}
@Immutable
public static class SymbolicParameterDeclarationListBuilder<T> {
private final T nextBuilder;
private final List<SymbolicParameterDeclaration> declarations = new ArrayList<>();
private final ExecuteOnEnd executeOnEnd;
public SymbolicParameterDeclarationListBuilder(T nextBuilder, ExecuteOnEnd executeOnEnd) {
this.nextBuilder = nextBuilder;
this.executeOnEnd = executeOnEnd;
}
public SymbolicParameterDeclarationListBuilder<T> real(String realType) {
declarations.add(new SymbolicParameterDeclaration(realType, false));
return this;
}
public SymbolicParameterDeclarationListBuilder<T> realArray(String realType, int dimensions) {
declarations.add(new SymbolicParameterDeclaration(realType, false, dimensions));
return this;
}
public SymbolicParameterDeclarationListBuilder<T> symbolic(String symbolicType) {
declarations.add(new SymbolicParameterDeclaration(symbolicType, true));
return this;
}
public SymbolicParameterDeclarationListBuilder<T> symbolicArray(String symbolicType, int dimensions) {
declarations.add(new SymbolicParameterDeclaration(symbolicType, true, dimensions));
return this;
}
public T end() {
executeOnEnd.run(new SymbolicParameterDeclarationList(declarations));
return nextBuilder;
}
}
private final List<SymbolicParameterDeclaration> declarations;
public SymbolicParameterDeclarationList(List<SymbolicParameterDeclaration> declarations) {
this.declarations = Collections.unmodifiableList(declarations);
}
public List<SymbolicParameterDeclaration> getDeclarations() {
return declarations;
}
public String getParameterString() {
String separator = "";
StringBuilder stringBuilder = new StringBuilder("(");
for (SymbolicParameterDeclaration declaration : declarations) {
stringBuilder.append(separator).append(declaration.getParameterString());
separator = ", ";
}
stringBuilder.append(")");
return stringBuilder.toString();
}
}
|
amidst
|
src\main\java\amidst\fragment\colorprovider\BackgroundColorProvider.java
|
package amidst.fragment.colorprovider;
import amidst.documentation.ThreadSafe;
import amidst.fragment.Fragment;
import amidst.logging.AmidstLogger;
import amidst.mojangapi.world.Dimension;
import amidst.mojangapi.world.biome.BiomeColor;
@ThreadSafe
public class BackgroundColorProvider implements ColorProvider {
private final BiomeColorProvider biomeColorProvider;
private final TheEndColorProvider theEndColorProvider;
public BackgroundColorProvider(BiomeColorProvider biomeColorProvider, TheEndColorProvider theEndColorProvider) {
this.biomeColorProvider = biomeColorProvider;
this.theEndColorProvider = theEndColorProvider;
}
@Override
public int getColorAt(Dimension dimension, Fragment fragment, long cornerX, long cornerY, int x, int y) {
if (dimension.equals(Dimension.OVERWORLD)) {
return biomeColorProvider.getColorAt(dimension, fragment, cornerX, cornerY, x, y);
} else if (dimension.equals(Dimension.END)) {
return theEndColorProvider.getColorAt(dimension, fragment, cornerX, cornerY, x, y);
} else {
AmidstLogger.warn("unsupported dimension");
return BiomeColor.unknown().getRGB();
}
}
}
|
amidst
|
src\main\java\amidst\fragment\colorprovider\BiomeColorProvider.java
|
package amidst.fragment.colorprovider;
import amidst.documentation.ThreadSafe;
import amidst.fragment.Fragment;
import amidst.gui.main.viewer.BiomeSelection;
import amidst.mojangapi.world.Dimension;
import amidst.mojangapi.world.biome.BiomeColor;
import amidst.settings.biomeprofile.BiomeProfileSelection;
@ThreadSafe
public class BiomeColorProvider implements ColorProvider {
private final BiomeSelection biomeSelection;
private final BiomeProfileSelection biomeProfileSelection;
public BiomeColorProvider(BiomeSelection biomeSelection, BiomeProfileSelection biomeProfileSelection) {
this.biomeSelection = biomeSelection;
this.biomeProfileSelection = biomeProfileSelection;
}
@Override
public int getColorAt(Dimension dimension, Fragment fragment, long cornerX, long cornerY, int x, int y) {
return getColor(fragment.getBiomeDataAt(x, y));
}
private int getColor(int biomeIndex) {
if (biomeSelection.isVisible(biomeIndex)) {
return getBiomeColor(biomeIndex).getRGB();
} else {
return getBiomeColor(biomeIndex).getHiddenRGB();
}
}
private BiomeColor getBiomeColor(int biomeIndex) {
return biomeProfileSelection.getBiomeColorOrUnknown(biomeIndex);
}
}
|
amidst
|
src\main\java\amidst\fragment\colorprovider\ColorProvider.java
|
package amidst.fragment.colorprovider;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.fragment.Fragment;
import amidst.mojangapi.world.Dimension;
public interface ColorProvider {
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
int getColorAt(Dimension dimension, Fragment fragment, long cornerX, long cornerY, int x, int y);
}
|
amidst
|
src\main\java\amidst\fragment\colorprovider\SlimeColorProvider.java
|
package amidst.fragment.colorprovider;
import amidst.documentation.ThreadSafe;
import amidst.fragment.Fragment;
import amidst.mojangapi.world.Dimension;
import amidst.mojangapi.world.oracle.SlimeChunkOracle;
@ThreadSafe
public class SlimeColorProvider implements ColorProvider {
private static final int SLIME_CHUNK_COLOR = 0xA0FE80FA;
private static final int NOT_SLIME_CHUNK_COLOR = 0x00000000;
private final SlimeChunkOracle slimeChunkOracle;
public SlimeColorProvider(SlimeChunkOracle slimeChunkOracle) {
this.slimeChunkOracle = slimeChunkOracle;
}
@Override
public int getColorAt(Dimension dimension, Fragment fragment, long cornerX, long cornerY, int x, int y) {
if (slimeChunkOracle.isSlimeChunk(cornerX + x, cornerY + y)) {
return SLIME_CHUNK_COLOR;
} else {
return NOT_SLIME_CHUNK_COLOR;
}
}
}
|
amidst
|
src\main\java\amidst\fragment\colorprovider\TheEndColorProvider.java
|
package amidst.fragment.colorprovider;
import java.awt.image.BufferedImage;
import java.util.List;
import amidst.ResourceLoader;
import amidst.documentation.ThreadSafe;
import amidst.fragment.Fragment;
import amidst.mojangapi.world.Dimension;
import amidst.mojangapi.world.oracle.EndIsland;
@ThreadSafe
public class TheEndColorProvider implements ColorProvider {
private static final int VOID_TRANSPARENT_BLACK = 0x00000000;
private static final BufferedImage TEXTURES = ResourceLoader.getImage("/amidst/gui/main/endtextures.png");
private static final int TEXTURES_WIDTH = TEXTURES.getWidth();
private static final int TEXTURES_HEIGHT = TEXTURES.getHeight() >> 1;
/**
* INFLUENCE_FADE_FINISH must be lower than INFLUENCE_FADE_START, so that
* islands fades out as influence declines.
*/
private static final float INFLUENCE_FADE_START = 0;
private static final float INFLUENCE_FADE_FINISH = -8;
private static final float INFLUENCE_FADE_RANGE = INFLUENCE_FADE_START - INFLUENCE_FADE_FINISH;
@Override
public int getColorAt(Dimension dimension, Fragment fragment, long cornerX, long cornerY, int x, int y) {
long xAsQuarter = cornerX + x;
long yAsQuarter = cornerY + y;
return getColorAt(
(int) (xAsQuarter << 2),
(int) (yAsQuarter << 2),
xAsQuarter >> 2,
yAsQuarter >> 2,
(int) (x % TEXTURES_WIDTH),
(int) (y % TEXTURES_HEIGHT),
fragment.getEndIslands());
}
private int getColorAt(
int x,
int y,
long chunkX,
long chunkY,
int textureX,
int textureY,
List<EndIsland> endIslands) {
// Determine whether this
float maxInfluence = getMaxInfluence(x, y, endIslands);
if (maxInfluence >= INFLUENCE_FADE_START) {
// Draw endstone island
return getEndStoneTextureAt(textureX, textureY);
} else {
return getFadingColorAt(chunkX, chunkY, textureX, textureY, maxInfluence);
}
}
private float getMaxInfluence(int x, int y, List<EndIsland> endIslands) {
float result = -100.0f;
for (EndIsland island : endIslands) {
float influence = island.influenceAtBlock(x, y);
if (result < influence) {
result = influence;
}
}
return result;
}
private int getFadingColorAt(long chunkX, long chunkY, int textureX, int textureY, float maxInfluence) {
int result = VOID_TRANSPARENT_BLACK;
if (showRockyShores(chunkX, chunkY)) {
result = getRockyShoresTextureAt(textureX, textureY);
}
if (maxInfluence > INFLUENCE_FADE_FINISH) {
// Fade out the endstone - this is the edge of an island
int pixelAlpha = result >>> 24;
int fadingIslandAlpha = getFadingIslandAlpha(maxInfluence);
if (fadingIslandAlpha > pixelAlpha) {
// favor the island pixel instead of the rocky shores pixel
// (Should look perfect without needing to blend, because
// rocky shore is still endstone texture)
return getFadedEndStoneTextureAt(textureX, textureY, fadingIslandAlpha);
}
}
return result;
}
/**
* Determine if the chunk may contain miniature islands.
*/
private boolean showRockyShores(long chunkX, long chunkY) {
return (chunkX * chunkX + chunkY * chunkY) > 4096;
}
private int getFadingIslandAlpha(float maxInfluence) {
return 255 - (int) (255 * (INFLUENCE_FADE_START - maxInfluence) / INFLUENCE_FADE_RANGE);
}
private int getEndStoneTextureAt(int textureX, int textureY) {
return TEXTURES.getRGB(textureX, textureY);
}
/**
* Unfortunately the "rocky shore" miniature islands are not deterministic
* from the world seed, like chorus plants they are decorations whose PRNG
* state depends on the order chunks are created/explored in. This makes me
* sad :( Let's use a symbolic texture, since we can't plot them properly.
*/
private int getRockyShoresTextureAt(int textureX, int textureY) {
return TEXTURES.getRGB(textureX, textureY + TEXTURES_HEIGHT);
}
private int getFadedEndStoneTextureAt(int textureX, int textureY, int alpha) {
return (getEndStoneTextureAt(textureX, textureY) & 0x00FFFFFF) | (alpha << 24);
}
}
|
amidst
|
src\main\java\amidst\fragment\constructor\BiomeDataConstructor.java
|
package amidst.fragment.constructor;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.Immutable;
import amidst.fragment.Fragment;
import amidst.mojangapi.world.coordinates.Resolution;
@Immutable
public class BiomeDataConstructor implements FragmentConstructor {
private final int size;
@CalledOnlyBy(AmidstThread.EDT)
public BiomeDataConstructor(Resolution resolution) {
this.size = resolution.getStepsPerFragment();
}
@CalledOnlyBy(AmidstThread.EDT)
@Override
public void construct(Fragment fragment) {
fragment.initBiomeData(size, size);
}
}
|
amidst
|
src\main\java\amidst\fragment\constructor\EndIslandsConstructor.java
|
package amidst.fragment.constructor;
import java.util.Collections;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.Immutable;
import amidst.fragment.Fragment;
@Immutable
public class EndIslandsConstructor implements FragmentConstructor {
@CalledOnlyBy(AmidstThread.EDT)
@Override
public void construct(Fragment fragment) {
fragment.setEndIslands(Collections.emptyList());
}
}
|
amidst
|
src\main\java\amidst\fragment\constructor\FragmentConstructor.java
|
package amidst.fragment.constructor;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.Immutable;
import amidst.fragment.Fragment;
@Immutable
public interface FragmentConstructor {
@CalledOnlyBy(AmidstThread.EDT)
void construct(Fragment fragment);
}
|
amidst
|
src\main\java\amidst\fragment\constructor\ImageConstructor.java
|
package amidst.fragment.constructor;
import java.awt.image.BufferedImage;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.Immutable;
import amidst.fragment.Fragment;
import amidst.mojangapi.world.coordinates.Resolution;
@Immutable
public class ImageConstructor implements FragmentConstructor {
private final int size;
private final int layerId;
@CalledOnlyBy(AmidstThread.EDT)
public ImageConstructor(Resolution resolution, int layerId) {
this.size = resolution.getStepsPerFragment();
this.layerId = layerId;
}
@CalledOnlyBy(AmidstThread.EDT)
@Override
public void construct(Fragment fragment) {
fragment.putImage(layerId, createBufferedImage());
}
@CalledOnlyBy(AmidstThread.EDT)
private BufferedImage createBufferedImage() {
return new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
}
}
|
amidst
|
src\main\java\amidst\fragment\drawer\AlphaUpdater.java
|
package amidst.fragment.drawer;
import java.awt.Graphics2D;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.fragment.Fragment;
import amidst.fragment.layer.LayerDeclaration;
@NotThreadSafe
public class AlphaUpdater extends FragmentDrawer {
public AlphaUpdater(LayerDeclaration declaration) {
super(declaration);
}
@CalledOnlyBy(AmidstThread.EDT)
@Override
public void draw(Fragment fragment, Graphics2D g2d, float time) {
fragment.setAlpha(Math.min(1.0f, time * 3.0f + fragment.getAlpha()));
}
}
|
amidst
|
src\main\java\amidst\fragment\drawer\FragmentDrawer.java
|
package amidst.fragment.drawer;
import java.awt.Graphics2D;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.fragment.Fragment;
import amidst.fragment.layer.LayerDeclaration;
@NotThreadSafe
public abstract class FragmentDrawer {
protected final LayerDeclaration declaration;
public FragmentDrawer(LayerDeclaration declaration) {
this.declaration = declaration;
}
@CalledOnlyBy(AmidstThread.EDT)
public boolean isEnabled() {
return declaration.isVisible();
}
@CalledOnlyBy(AmidstThread.EDT)
public boolean isDrawUnloaded() {
return declaration.isDrawUnloaded();
}
@CalledOnlyBy(AmidstThread.EDT)
public abstract void draw(Fragment fragment, Graphics2D g2d, float time);
}
|
amidst
|
src\main\java\amidst\fragment\drawer\GridDrawer.java
|
package amidst.fragment.drawer;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.fragment.Fragment;
import amidst.fragment.layer.LayerDeclaration;
import amidst.gui.main.viewer.Zoom;
import amidst.mojangapi.world.coordinates.Resolution;
@NotThreadSafe
public class GridDrawer extends FragmentDrawer {
private static final Font DRAW_FONT = new Font("arial", Font.BOLD, 16);
private final StringBuffer textBuffer = new StringBuffer(128);
private final char[] textCache = new char[128];
private final Zoom zoom;
public GridDrawer(LayerDeclaration declaration, Zoom zoom) {
super(declaration);
this.zoom = zoom;
}
@CalledOnlyBy(AmidstThread.EDT)
@Override
public void draw(Fragment fragment, Graphics2D g2d, float time) {
int stride = getStride();
int gridX = getGridX(fragment, stride);
int gridY = getGridY(fragment, stride);
initGraphics(g2d);
drawGridLines(g2d, stride, gridX, gridY);
if (isGrid00(gridX, gridY)) {
double invZoom = 1.0 / zoom.getCurrentValue();
g2d.scale(invZoom, invZoom);
updateText(fragment);
drawText(g2d);
// drawThickTextOutline(g2d);
drawTextOutline(g2d);
}
}
@CalledOnlyBy(AmidstThread.EDT)
private int getStride() {
return (int) (.25 / zoom.getCurrentValue());
}
@CalledOnlyBy(AmidstThread.EDT)
private int getGridX(Fragment fragment, int stride) {
return (int) fragment.getCorner().getXAs(Resolution.FRAGMENT) % (stride + 1);
}
@CalledOnlyBy(AmidstThread.EDT)
private int getGridY(Fragment fragment, int stride) {
return (int) fragment.getCorner().getYAs(Resolution.FRAGMENT) % (stride + 1);
}
@CalledOnlyBy(AmidstThread.EDT)
private void initGraphics(Graphics2D g2d) {
g2d.setFont(DRAW_FONT);
g2d.setColor(Color.black);
}
@CalledOnlyBy(AmidstThread.EDT)
private void drawGridLines(Graphics2D g2d, int stride, int gridX, int gridY) {
if (gridY == 0) {
g2d.drawLine(0, 0, Fragment.SIZE, 0);
}
if (gridY == stride) {
g2d.drawLine(0, Fragment.SIZE, Fragment.SIZE, Fragment.SIZE);
}
if (gridX == 0) {
g2d.drawLine(0, 0, 0, Fragment.SIZE);
}
if (gridX == stride) {
g2d.drawLine(Fragment.SIZE, 0, Fragment.SIZE, Fragment.SIZE);
}
}
@CalledOnlyBy(AmidstThread.EDT)
private boolean isGrid00(int gridX, int gridY) {
return gridX == 0 && gridY == 0;
}
@CalledOnlyBy(AmidstThread.EDT)
private void updateText(Fragment fragment) {
textBuffer.setLength(0);
textBuffer.append(fragment.getCorner().getX());
textBuffer.append(", ");
textBuffer.append(fragment.getCorner().getY());
textBuffer.getChars(0, textBuffer.length(), textCache, 0);
}
@CalledOnlyBy(AmidstThread.EDT)
private void drawText(Graphics2D g2d) {
g2d.drawChars(textCache, 0, textBuffer.length(), 12, 17);
g2d.drawChars(textCache, 0, textBuffer.length(), 8, 17);
g2d.drawChars(textCache, 0, textBuffer.length(), 10, 19);
g2d.drawChars(textCache, 0, textBuffer.length(), 10, 15);
}
// This makes the text outline a bit thicker, but seems unneeded.
@SuppressWarnings("unused")
private void drawThickTextOutline(Graphics2D g2d) {
g2d.drawChars(textCache, 0, textBuffer.length(), 12, 15);
g2d.drawChars(textCache, 0, textBuffer.length(), 12, 19);
g2d.drawChars(textCache, 0, textBuffer.length(), 8, 15);
g2d.drawChars(textCache, 0, textBuffer.length(), 8, 19);
}
@CalledOnlyBy(AmidstThread.EDT)
private void drawTextOutline(Graphics2D g2d) {
g2d.setColor(Color.white);
g2d.drawChars(textCache, 0, textBuffer.length(), 10, 17);
}
}
|
amidst
|
src\main\java\amidst\fragment\drawer\ImageDrawer.java
|
package amidst.fragment.drawer;
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.VolatileImage;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.fragment.Fragment;
import amidst.fragment.layer.LayerDeclaration;
import amidst.gui.main.viewer.Graphics2DAccelerationCounter;
import amidst.mojangapi.world.coordinates.Resolution;
import amidst.settings.Setting;
@NotThreadSafe
public class ImageDrawer extends FragmentDrawer {
private final Resolution resolution;
private final Graphics2DAccelerationCounter accelerationCounter;
private final Setting<Boolean> useHybridScaling;
public ImageDrawer(
LayerDeclaration declaration,
Resolution resolution,
Graphics2DAccelerationCounter accelerationCounter,
Setting<Boolean> useHybridScaling) {
super(declaration);
this.resolution = resolution;
this.accelerationCounter = accelerationCounter;
this.useHybridScaling = useHybridScaling;
}
@Override
public void draw(Fragment fragment, Graphics2D g2d, float time) {
if (useHybridScaling.get()) {
drawHybrid(fragment, g2d, time);
} else {
drawNearest(fragment, g2d, time);
}
}
@CalledOnlyBy(AmidstThread.EDT)
private void drawNearest(Fragment fragment, Graphics2D g2d, float time) {
int scale = resolution.getStep();
g2d.scale(scale, scale);
Object oldHint = g2d.getRenderingHint(RenderingHints.KEY_INTERPOLATION);
Object newHint = getRenderingHint(g2d);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, newHint);
BufferedImage image = fragment.getImage(declaration.getLayerId());
accelerationCounter.log(image);
g2d.drawImage(image, 0, 0, null);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, oldHint);
}
@CalledOnlyBy(AmidstThread.EDT)
private Object getRenderingHint(Graphics2D g2d) {
if (g2d.getTransform().getScaleX() < 1.0f) {
return RenderingHints.VALUE_INTERPOLATION_BILINEAR;
} else {
return RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR;
}
}
private static final GraphicsConfiguration GC = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice()
.getDefaultConfiguration();
private VolatileImage tempImage;
/**
* This sets the amount of deviation in the pixels that nearest
* neighbor can have.
*/
private static final double NEAREST_PIXEL_THRESHOLD = 1.0d;
/**
* When drawing with this method, we scale the image with a hybrid of
* both nearest neighbor and bilinear. As an example, lets say that
* the scale of the g2d is 3.2. We want to split the 3.2 into 3.0 and
* 0.2. The nearest neighbor algorithm then scales it up by 3.0 and
* stores it into a temporary image. Then, the bilinear algorithm
* scales up the temporary image by whatever it needs to get 3.0 to
* 3.2. In this case, it would be 1.066 repeating.
*
* This gives the upsides of both nearest neighbor for image
* preservation and bilinear for smooth edges at irregular scales.
*/
@CalledOnlyBy(AmidstThread.EDT)
private void drawHybrid(Fragment fragment, Graphics2D g2d, float time) {
int scale = resolution.getStep();
g2d.scale(scale, scale);
Object oldHint = g2d.getRenderingHint(RenderingHints.KEY_INTERPOLATION);
Image image = fragment.getImage(declaration.getLayerId());
double scaleX = g2d.getTransform().getScaleX(); // This could be the Y value, but it shouldn't matter because they should be equal
double nearestScale = Math.floor(scaleX); // scale value for nearest neighbor pass (if applicable)
int imageWidth = image.getWidth(null);
// this checks to see if the scale lies within the amount that the scale can deviate before changing pixels
double threshold = ((NEAREST_PIXEL_THRESHOLD / imageWidth) * nearestScale) / scale;
double check = Math.abs(scaleX - Math.round(scaleX)); // works for checking above or below
if(check > threshold) {
if (scaleX > 2.0) { // this algorithm has no benefit if the scale is less than 2
double bilinearScale = scaleX / nearestScale; // scale value for bilinear pass
int nearestSize = (int) (imageWidth * nearestScale);
// recreate volatile image if it's been messed up in some way
if (tempImage == null || tempImage.getWidth() != nearestSize || tempImage.validate(GC) == VolatileImage.IMAGE_INCOMPATIBLE) {
tempImage = GC.createCompatibleVolatileImage(nearestSize, nearestSize, Transparency.TRANSLUCENT);
}
// create a g2d for the temporary image and scales the original with nearest neighbor into it
Graphics2D g2dTemp = tempImage.createGraphics();
g2dTemp.setComposite(AlphaComposite.Src); // fixes the transparency being wrong
g2dTemp.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
g2dTemp.scale(nearestScale, nearestScale);
accelerationCounter.log(image);
g2dTemp.drawImage(image, 0, 0, null);
g2dTemp.dispose();
// set them main g2d to be ready to apply the bilinear scaling
// for some reason, g2d doesn't let us directly change the transform's variables easily
// this means that we have to multiply our bilinear scale by the inverse of the current scale to cancel out the current scale
double bilinearScaleModified = (1 / scaleX) * bilinearScale;
g2d.scale(bilinearScaleModified, bilinearScaleModified);
image = tempImage;
}
// if the scale isn't an integer, set the main g2d to bilinear
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
} else {
// if nearest neighbor is within the threshold to where it wouldn't badly modify any pixels, use it
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
}
accelerationCounter.log(image);
g2d.drawImage(image, 0, 0, null);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, oldHint);
}
}
|
amidst
|
src\main\java\amidst\fragment\drawer\WorldIconDrawer.java
|
package amidst.fragment.drawer;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.fragment.Fragment;
import amidst.fragment.layer.LayerDeclaration;
import amidst.gui.main.viewer.WorldIconSelection;
import amidst.gui.main.viewer.Zoom;
import amidst.mojangapi.world.coordinates.CoordinatesInWorld;
import amidst.mojangapi.world.icon.WorldIcon;
import amidst.settings.Setting;
@NotThreadSafe
public class WorldIconDrawer extends FragmentDrawer {
private final Zoom zoom;
private final WorldIconSelection worldIconSelection;
private final Setting<Boolean> useHybridScaling;
public WorldIconDrawer(
LayerDeclaration declaration,
Zoom zoom,
WorldIconSelection worldIconSelection,
Setting<Boolean> useHybridScaling) {
super(declaration);
this.zoom = zoom;
this.worldIconSelection = worldIconSelection;
this.useHybridScaling = useHybridScaling;
}
@CalledOnlyBy(AmidstThread.EDT)
@Override
public void draw(Fragment fragment, Graphics2D g2d, float time) {
double invZoom = 1.0 / zoom.getCurrentValue();
Object oldHint = g2d.getRenderingHint(RenderingHints.KEY_INTERPOLATION);
AffineTransform originalTransform = g2d.getTransform();
for (WorldIcon icon : fragment.getWorldIcons(declaration.getLayerId())) {
drawIcon(icon, invZoom, g2d);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, oldHint);
g2d.setTransform(originalTransform);
}
}
@CalledOnlyBy(AmidstThread.EDT)
private void drawIcon(WorldIcon icon, double invZoom, Graphics2D g2d) {
BufferedImage image = icon.getImage().getImage();
int width = image.getWidth();
int height = image.getHeight();
if (worldIconSelection.isSelected(icon)) {
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, getInterpolationHint());
width *= 1.5;
height *= 1.5;
}
CoordinatesInWorld coordinates = icon.getCoordinates();
g2d.translate(coordinates.getXRelativeToFragment(), coordinates.getYRelativeToFragment());
g2d.scale(invZoom, invZoom);
g2d.drawImage(image, -(width >> 1), -(height >> 1), width, height, null);
}
@CalledOnlyBy(AmidstThread.EDT)
private Object getInterpolationHint() {
if (useHybridScaling.get()) {
return RenderingHints.VALUE_INTERPOLATION_BICUBIC;
} else {
return RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR;
}
}
}
|
amidst
|
src\main\java\amidst\fragment\layer\LayerBuilder.java
|
package amidst.fragment.layer;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import amidst.AmidstSettings;
import amidst.documentation.Immutable;
import amidst.fragment.Fragment;
import amidst.fragment.colorprovider.BackgroundColorProvider;
import amidst.fragment.colorprovider.BiomeColorProvider;
import amidst.fragment.colorprovider.SlimeColorProvider;
import amidst.fragment.colorprovider.TheEndColorProvider;
import amidst.fragment.constructor.BiomeDataConstructor;
import amidst.fragment.constructor.EndIslandsConstructor;
import amidst.fragment.constructor.FragmentConstructor;
import amidst.fragment.constructor.ImageConstructor;
import amidst.fragment.drawer.AlphaUpdater;
import amidst.fragment.drawer.FragmentDrawer;
import amidst.fragment.drawer.GridDrawer;
import amidst.fragment.drawer.ImageDrawer;
import amidst.fragment.drawer.WorldIconDrawer;
import amidst.fragment.loader.AlphaInitializer;
import amidst.fragment.loader.BiomeDataLoader;
import amidst.fragment.loader.EndIslandsLoader;
import amidst.fragment.loader.FragmentLoader;
import amidst.fragment.loader.ImageLoader;
import amidst.fragment.loader.WorldIconLoader;
import amidst.gui.main.viewer.BiomeSelection;
import amidst.gui.main.viewer.Graphics2DAccelerationCounter;
import amidst.gui.main.viewer.WorldIconSelection;
import amidst.gui.main.viewer.Zoom;
import amidst.mojangapi.world.Dimension;
import amidst.mojangapi.world.World;
import amidst.mojangapi.world.coordinates.Resolution;
import amidst.settings.Setting;
@Immutable
public class LayerBuilder {
private final Iterable<FragmentConstructor> constructors;
public LayerBuilder() {
this.constructors = createConstructors();
}
/**
* This also defines the construction order.
*/
private Iterable<FragmentConstructor> createConstructors() {
return Collections.unmodifiableList(
Arrays.asList(
new BiomeDataConstructor(Resolution.QUARTER),
new EndIslandsConstructor(),
new ImageConstructor(Resolution.QUARTER, LayerIds.BACKGROUND),
new ImageConstructor(Resolution.CHUNK, LayerIds.SLIME)));
}
public Iterable<FragmentConstructor> getConstructors() {
return constructors;
}
public int getNumberOfLayers() {
return LayerIds.NUMBER_OF_LAYERS;
}
public LayerManager create(
AmidstSettings settings,
World world,
BiomeSelection biomeSelection,
WorldIconSelection worldIconSelection,
Zoom zoom,
Graphics2DAccelerationCounter accelerationCounter) {
List<LayerDeclaration> declarations = createDeclarations(settings, world.getEnabledLayers());
return new LayerManager(
declarations,
new LayerLoader(
createLoaders(declarations, world, biomeSelection, settings),
LayerIds.NUMBER_OF_LAYERS),
createDrawers(declarations, zoom, worldIconSelection, accelerationCounter,
settings)
);
}
private List<LayerDeclaration> createDeclarations(AmidstSettings settings, List<Integer> enabledLayers) {
LayerDeclaration[] declarations = new LayerDeclaration[LayerIds.NUMBER_OF_LAYERS];
// @formatter:off
declare(settings, declarations, enabledLayers, LayerIds.ALPHA, null, false, Setting.createImmutable(true));
declare(settings, declarations, enabledLayers, LayerIds.BIOME_DATA, Dimension.OVERWORLD, false, Setting.createImmutable(true));
declare(settings, declarations, enabledLayers, LayerIds.END_ISLANDS, Dimension.END, false, Setting.createImmutable(true));
declare(settings, declarations, enabledLayers, LayerIds.BACKGROUND, null, false, Setting.createImmutable(true));
declare(settings, declarations, enabledLayers, LayerIds.SLIME, Dimension.OVERWORLD, false, settings.showSlimeChunks);
declare(settings, declarations, enabledLayers, LayerIds.GRID, null, true, settings.showGrid);
declare(settings, declarations, enabledLayers, LayerIds.SPAWN, Dimension.OVERWORLD, false, settings.showSpawn);
declare(settings, declarations, enabledLayers, LayerIds.STRONGHOLD, Dimension.OVERWORLD, false, settings.showStrongholds);
declare(settings, declarations, enabledLayers, LayerIds.PLAYER, null, false, settings.showPlayers);
declare(settings, declarations, enabledLayers, LayerIds.VILLAGE, Dimension.OVERWORLD, false, settings.showVillages);
declare(settings, declarations, enabledLayers, LayerIds.TEMPLE, Dimension.OVERWORLD, false, settings.showTemples);
declare(settings, declarations, enabledLayers, LayerIds.MINESHAFT, Dimension.OVERWORLD, false, settings.showMineshafts);
declare(settings, declarations, enabledLayers, LayerIds.OCEAN_MONUMENT, Dimension.OVERWORLD, false, settings.showOceanMonuments);
declare(settings, declarations, enabledLayers, LayerIds.WOODLAND_MANSION,Dimension.OVERWORLD, false, settings.showWoodlandMansions);
declare(settings, declarations, enabledLayers, LayerIds.OCEAN_FEATURES, Dimension.OVERWORLD, false, settings.showOceanFeatures);
declare(settings, declarations, enabledLayers, LayerIds.NETHER_FEATURES, Dimension.OVERWORLD, false, settings.showNetherFortresses);
declare(settings, declarations, enabledLayers, LayerIds.END_CITY, Dimension.END, false, settings.showEndCities);
// @formatter:on
return Collections.unmodifiableList(Arrays.asList(declarations));
}
private void declare(
AmidstSettings settings,
LayerDeclaration[] declarations,
List<Integer> enabledLayers,
int layerId,
Dimension dimension,
boolean drawUnloaded,
Setting<Boolean> isVisibleSetting) {
declarations[layerId] = new LayerDeclaration(
layerId,
dimension,
drawUnloaded,
enabledLayers.contains(layerId),
isVisibleSetting);
}
/**
* This also defines the loading and reloading order.
*/
private Iterable<FragmentLoader> createLoaders(
List<LayerDeclaration> declarations,
World world,
BiomeSelection biomeSelection,
AmidstSettings settings) {
// @formatter:off
return Collections.unmodifiableList(Arrays.asList(
new AlphaInitializer( declarations.get(LayerIds.ALPHA), settings.fragmentFading),
new BiomeDataLoader( declarations.get(LayerIds.BIOME_DATA), world.getOverworldBiomeDataOracle()),
new EndIslandsLoader( declarations.get(LayerIds.END_ISLANDS), world.getEndIslandOracle()),
new ImageLoader( declarations.get(LayerIds.BACKGROUND), Resolution.QUARTER, new BackgroundColorProvider(new BiomeColorProvider(biomeSelection, settings.biomeProfileSelection), new TheEndColorProvider())),
new ImageLoader( declarations.get(LayerIds.SLIME), Resolution.CHUNK, new SlimeColorProvider(world.getSlimeChunkOracle())),
new WorldIconLoader<>(declarations.get(LayerIds.SPAWN), world.getSpawnProducer()),
new WorldIconLoader<>(declarations.get(LayerIds.STRONGHOLD), world.getStrongholdProducer()),
new WorldIconLoader<>(declarations.get(LayerIds.PLAYER), world.getPlayerProducer()),
new WorldIconLoader<>(declarations.get(LayerIds.VILLAGE), world.getVillageProducer()),
new WorldIconLoader<>(declarations.get(LayerIds.TEMPLE), world.getTempleProducer()),
new WorldIconLoader<>(declarations.get(LayerIds.MINESHAFT), world.getMineshaftProducer()),
new WorldIconLoader<>(declarations.get(LayerIds.OCEAN_MONUMENT), world.getOceanMonumentProducer()),
new WorldIconLoader<>(declarations.get(LayerIds.WOODLAND_MANSION),world.getWoodlandMansionProducer()),
new WorldIconLoader<>(declarations.get(LayerIds.OCEAN_FEATURES), world.getOceanFeaturesProducer()),
new WorldIconLoader<>(declarations.get(LayerIds.NETHER_FEATURES), world.getNetherFortressProducer()),
new WorldIconLoader<>(declarations.get(LayerIds.END_CITY), world.getEndCityProducer(), Fragment::getEndIslands)
));
// @formatter:on
}
/**
* This also defines the rendering order.
*/
private Iterable<FragmentDrawer> createDrawers(
List<LayerDeclaration> declarations,
Zoom zoom,
WorldIconSelection worldIconSelection,
Graphics2DAccelerationCounter accelerationCounter,
AmidstSettings settings) {
// @formatter:off
return Collections.unmodifiableList(Arrays.asList(
new AlphaUpdater( declarations.get(LayerIds.ALPHA)),
new ImageDrawer( declarations.get(LayerIds.BACKGROUND), Resolution.QUARTER, accelerationCounter, settings.useHybridScaling),
new ImageDrawer( declarations.get(LayerIds.SLIME), Resolution.CHUNK, accelerationCounter, settings.useHybridScaling),
new GridDrawer( declarations.get(LayerIds.GRID), zoom),
new WorldIconDrawer(declarations.get(LayerIds.SPAWN), zoom, worldIconSelection, settings.useHybridScaling),
new WorldIconDrawer(declarations.get(LayerIds.STRONGHOLD), zoom, worldIconSelection, settings.useHybridScaling),
new WorldIconDrawer(declarations.get(LayerIds.PLAYER), zoom, worldIconSelection, settings.useHybridScaling),
new WorldIconDrawer(declarations.get(LayerIds.VILLAGE), zoom, worldIconSelection, settings.useHybridScaling),
new WorldIconDrawer(declarations.get(LayerIds.TEMPLE), zoom, worldIconSelection, settings.useHybridScaling),
new WorldIconDrawer(declarations.get(LayerIds.MINESHAFT), zoom, worldIconSelection, settings.useHybridScaling),
new WorldIconDrawer(declarations.get(LayerIds.OCEAN_MONUMENT), zoom, worldIconSelection, settings.useHybridScaling),
new WorldIconDrawer(declarations.get(LayerIds.WOODLAND_MANSION),zoom, worldIconSelection, settings.useHybridScaling),
new WorldIconDrawer(declarations.get(LayerIds.OCEAN_FEATURES), zoom, worldIconSelection, settings.useHybridScaling),
new WorldIconDrawer(declarations.get(LayerIds.NETHER_FEATURES), zoom, worldIconSelection, settings.useHybridScaling),
new WorldIconDrawer(declarations.get(LayerIds.END_CITY), zoom, worldIconSelection, settings.useHybridScaling)
));
// @formatter:on
}
}
|
amidst
|
src\main\java\amidst\fragment\layer\LayerDeclaration.java
|
package amidst.fragment.layer;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledByAny;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.mojangapi.world.Dimension;
import amidst.settings.Setting;
@NotThreadSafe
public class LayerDeclaration {
private final int layerId;
private final Dimension dimension;
private final boolean isDrawUnloaded;
private final boolean isSupportedInCurrentVersion;
private final Setting<Boolean> isVisibleSetting;
private volatile boolean isVisible;
/**
* @param dimension Can be null to enable for all dimensions.
*/
public LayerDeclaration(
int layerId,
Dimension dimension,
boolean drawUnloaded,
boolean isSupportedInCurrentVersion,
Setting<Boolean> isVisibleSetting) {
this.layerId = layerId;
this.dimension = dimension;
this.isDrawUnloaded = drawUnloaded;
this.isSupportedInCurrentVersion = isSupportedInCurrentVersion;
this.isVisibleSetting = isVisibleSetting;
}
public int getLayerId() {
return layerId;
}
public boolean isDrawUnloaded() {
return isDrawUnloaded;
}
public boolean isVisible() {
return isVisible;
}
/**
* Updates the isVisible and isEnabled fields to the current setting values.
* Returns whether the layer becomes visible.
*/
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
public boolean update(Dimension dimension) {
boolean isEnabled = calculateIsEnabled(dimension);
boolean isVisible = isEnabled && isVisibleSetting.get();
boolean reload = isVisible == true && this.isVisible == false;
this.isVisible = isVisible;
return reload;
}
@CalledByAny
public boolean calculateIsEnabled(Dimension dimension) {
return isMatchingDimension(dimension) && isMatchingVersion();
}
@CalledByAny
private boolean isMatchingDimension(Dimension dimension) {
return this.dimension == null || this.dimension.equals(dimension);
}
@CalledByAny
private boolean isMatchingVersion() {
return isSupportedInCurrentVersion;
}
}
|
amidst
|
src\main\java\amidst\fragment\layer\LayerIds.java
|
package amidst.fragment.layer;
import amidst.documentation.Immutable;
/**
* The Ids are used as array indices but they do not influence the loading or
* drawing order.
*/
@Immutable
public class LayerIds {
// @formatter:off
public static final int ALPHA = 0;
public static final int BIOME_DATA = 1;
public static final int END_ISLANDS = 2;
public static final int BACKGROUND = 3;
public static final int SLIME = 4;
public static final int GRID = 5;
public static final int SPAWN = 6;
public static final int STRONGHOLD = 7;
public static final int PLAYER = 8;
public static final int VILLAGE = 9;
public static final int TEMPLE = 10;
public static final int MINESHAFT = 11;
public static final int OCEAN_MONUMENT = 12;
public static final int WOODLAND_MANSION = 13;
public static final int OCEAN_FEATURES = 14;
public static final int NETHER_FEATURES = 15;
public static final int END_CITY = 16;
public static final int NUMBER_OF_LAYERS = 17;
// @formatter:on
}
|
amidst
|
src\main\java\amidst\fragment\layer\LayerLoader.java
|
package amidst.fragment.layer;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledByAny;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.fragment.Fragment;
import amidst.fragment.loader.FragmentLoader;
import amidst.mojangapi.world.Dimension;
@NotThreadSafe
public class LayerLoader {
private final Iterable<FragmentLoader> loaders;
private final boolean[] invalidatedLayers;
@CalledByAny
public LayerLoader(Iterable<FragmentLoader> loaders, int numberOfLayers) {
this.loaders = loaders;
this.invalidatedLayers = new boolean[numberOfLayers];
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
public void clearInvalidatedLayers() {
for (int i = 0; i < invalidatedLayers.length; i++) {
invalidatedLayers[i] = false;
}
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
public void invalidateLayer(int layerId) {
invalidatedLayers[layerId] = true;
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
public void loadAll(Dimension dimension, Fragment fragment) {
for (FragmentLoader loader : loaders) {
if (loader.isEnabled()) {
loader.load(dimension, fragment);
}
}
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
public void reloadInvalidated(Dimension dimension, Fragment fragment) {
for (FragmentLoader loader : loaders) {
if (loader.isEnabled() && isInvalidated(loader.getLayerId())) {
loader.reload(dimension, fragment);
}
}
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
private boolean isInvalidated(int layerId) {
return invalidatedLayers[layerId];
}
}
|
amidst
|
src\main\java\amidst\fragment\layer\LayerManager.java
|
package amidst.fragment.layer;
import java.util.List;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledByAny;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.fragment.Fragment;
import amidst.fragment.drawer.FragmentDrawer;
import amidst.mojangapi.world.Dimension;
import amidst.mojangapi.world.World;
import amidst.threading.TaskQueue;
@NotThreadSafe
public class LayerManager {
private final TaskQueue invalidationOperations = new TaskQueue();
private final List<LayerDeclaration> declarations;
private final LayerLoader layerLoader;
private final Iterable<FragmentDrawer> drawers;
public LayerManager(
List<LayerDeclaration> declarations,
LayerLoader layerLoader,
Iterable<FragmentDrawer> drawers) {
this.declarations = declarations;
this.layerLoader = layerLoader;
this.drawers = drawers;
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
public boolean updateAll(Dimension dimension) {
for (LayerDeclaration declaration : declarations) {
if (declaration.update(dimension)) {
int layerId = declaration.getLayerId();
if (layerId == LayerIds.BIOME_DATA || layerId == LayerIds.END_ISLANDS) {
invalidateLayer(LayerIds.BACKGROUND);
}
invalidateLayer(layerId);
}
}
return invalidationOperations.processTasks();
}
@CalledByAny
public void invalidateLayer(int layerId) {
invalidationOperations.invoke(() -> doInvalidateLayer(layerId));
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
private void doInvalidateLayer(int layerId) {
layerLoader.invalidateLayer(layerId);
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
public void loadAll(Dimension dimension, Fragment fragment) {
layerLoader.loadAll(dimension, fragment);
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
public void reloadInvalidated(Dimension dimension, Fragment fragment) {
layerLoader.reloadInvalidated(dimension, fragment);
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
public void clearInvalidatedLayers() {
layerLoader.clearInvalidatedLayers();
}
public Iterable<LayerDeclaration> getDeclarations() {
return declarations;
}
public Iterable<FragmentDrawer> getDrawers() {
return drawers;
}
public LayerReloader createLayerReloader(World world) {
return new LayerReloader(world, this);
}
/**
* This should only be used by the layers menu.
*/
@CalledOnlyBy(AmidstThread.EDT)
public boolean calculateIsEnabled(int layerId, Dimension dimension) {
return declarations.get(layerId).calculateIsEnabled(dimension);
}
}
|
amidst
|
src\main\java\amidst\fragment\layer\LayerReloader.java
|
package amidst.fragment.layer;
import amidst.documentation.ThreadSafe;
import amidst.mojangapi.world.World;
@ThreadSafe
public class LayerReloader {
private final World world;
private final LayerManager layerManager;
public LayerReloader(World world, LayerManager layerManager) {
this.world = world;
this.layerManager = layerManager;
}
public void reloadBackgroundLayer() {
layerManager.invalidateLayer(LayerIds.BACKGROUND);
}
public void reloadPlayerLayer() {
world.reloadPlayerWorldIcons();
layerManager.invalidateLayer(LayerIds.PLAYER);
}
}
|
amidst
|
src\main\java\amidst\fragment\loader\AlphaInitializer.java
|
package amidst.fragment.loader;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.fragment.Fragment;
import amidst.fragment.layer.LayerDeclaration;
import amidst.mojangapi.world.Dimension;
import amidst.settings.Setting;
@NotThreadSafe
public class AlphaInitializer extends FragmentLoader {
private final Setting<Boolean> fragmentFadingSetting;
public AlphaInitializer(LayerDeclaration declaration, Setting<Boolean> fragmentFadingSetting) {
super(declaration);
this.fragmentFadingSetting = fragmentFadingSetting;
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
@Override
public void load(Dimension dimension, Fragment fragment) {
if (fragmentFadingSetting.get()) {
fragment.setAlpha(0.0f);
} else {
fragment.setAlpha(1.0f);
}
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
@Override
public void reload(Dimension dimension, Fragment fragment) {
// noop
}
}
|
amidst
|
src\main\java\amidst\fragment\loader\BiomeDataLoader.java
|
package amidst.fragment.loader;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.fragment.Fragment;
import amidst.fragment.layer.LayerDeclaration;
import amidst.mojangapi.world.Dimension;
import amidst.mojangapi.world.oracle.BiomeDataOracle;
@NotThreadSafe
public class BiomeDataLoader extends FragmentLoader {
private final BiomeDataOracle biomeDataOracle;
public BiomeDataLoader(LayerDeclaration declaration, BiomeDataOracle biomeDataOracle) {
super(declaration);
this.biomeDataOracle = biomeDataOracle;
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
@Override
public void load(Dimension dimension, Fragment fragment) {
doLoad(fragment);
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
@Override
public void reload(Dimension dimension, Fragment fragment) {
doLoad(fragment);
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
private void doLoad(Fragment fragment) {
fragment.populateBiomeData(biomeDataOracle);
}
}
|
amidst
|
src\main\java\amidst\fragment\loader\EndIslandsLoader.java
|
package amidst.fragment.loader;
import java.util.List;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledByAny;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.fragment.Fragment;
import amidst.fragment.layer.LayerDeclaration;
import amidst.mojangapi.world.Dimension;
import amidst.mojangapi.world.coordinates.CoordinatesInWorld;
import amidst.mojangapi.world.oracle.EndIsland;
import amidst.mojangapi.world.oracle.EndIslandOracle;
//TODO: use longs?
@NotThreadSafe
public class EndIslandsLoader extends FragmentLoader {
private final EndIslandOracle endIslandOracle;
@CalledByAny
public EndIslandsLoader(LayerDeclaration declaration, EndIslandOracle endIslandOracle) {
super(declaration);
this.endIslandOracle = endIslandOracle;
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
@Override
public void load(Dimension dimension, Fragment fragment) {
doLoad(fragment);
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
@Override
public void reload(Dimension dimension, Fragment fragment) {
doLoad(fragment);
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
private void doLoad(Fragment fragment) {
fragment.setEndIslands(getEndIslands(fragment.getCorner()));
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
private List<EndIsland> getEndIslands(CoordinatesInWorld corner) {
return endIslandOracle.getAt(corner);
}
}
|
amidst
|
src\main\java\amidst\fragment\loader\FragmentLoader.java
|
package amidst.fragment.loader;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.fragment.Fragment;
import amidst.fragment.layer.LayerDeclaration;
import amidst.mojangapi.world.Dimension;
@NotThreadSafe
public abstract class FragmentLoader {
protected final LayerDeclaration declaration;
public FragmentLoader(LayerDeclaration declaration) {
this.declaration = declaration;
}
public int getLayerId() {
return declaration.getLayerId();
}
public boolean isEnabled() {
return declaration.isVisible();
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
public abstract void load(Dimension dimension, Fragment fragment);
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
public abstract void reload(Dimension dimension, Fragment fragment);
}
|
amidst
|
src\main\java\amidst\fragment\loader\ImageLoader.java
|
package amidst.fragment.loader;
import java.awt.image.BufferedImage;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledByAny;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.ThreadSafe;
import amidst.fragment.Fragment;
import amidst.fragment.colorprovider.ColorProvider;
import amidst.fragment.layer.LayerDeclaration;
import amidst.mojangapi.world.Dimension;
import amidst.mojangapi.world.coordinates.CoordinatesInWorld;
import amidst.mojangapi.world.coordinates.Resolution;
@ThreadSafe
public class ImageLoader extends FragmentLoader {
private final Resolution resolution;
private final ColorProvider colorProvider;
private final int width, height;
@CalledByAny
public ImageLoader(LayerDeclaration declaration, Resolution resolution, ColorProvider colorProvider) {
super(declaration);
this.resolution = resolution;
this.colorProvider = colorProvider;
this.width = resolution.getStepsPerFragment();
this.height = resolution.getStepsPerFragment();
}
@CalledByAny
private BufferedImage createBufferedImage() {
return new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
@Override
public void load(Dimension dimension, Fragment fragment) {
doLoad(dimension, fragment);
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
@Override
public void reload(Dimension dimension, Fragment fragment) {
doLoad(dimension, fragment);
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
private void doLoad(Dimension dimension, Fragment fragment) {
// Slightly faster and uses less ram, but not as safe
CoordinatesInWorld corner = fragment.getCorner();
long cornerX = corner.getXAs(resolution);
long cornerY = corner.getYAs(resolution);
drawToImage(dimension, fragment, cornerX, cornerY, fragment.getImage(declaration.getLayerId()));
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
private void doLoadAtomic(Dimension dimension, Fragment fragment) {
CoordinatesInWorld corner = fragment.getCorner();
long cornerX = corner.getXAs(resolution);
long cornerY = corner.getYAs(resolution);
BufferedImage tempImg = createBufferedImage();
drawToImage(dimension, fragment, cornerX, cornerY, tempImg);
fragment.putImage(declaration.getLayerId(), tempImg);
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
private void drawToImage(Dimension dimension, Fragment fragment, long cornerX, long cornerY, BufferedImage bufferedImage) {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
bufferedImage.setRGB(x, y, colorProvider.getColorAt(dimension, fragment, cornerX, cornerY, x, y));
}
}
}
}
|
amidst
|
src\main\java\amidst\fragment\loader\WorldIconLoader.java
|
package amidst.fragment.loader;
import java.util.function.Function;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.fragment.Fragment;
import amidst.fragment.layer.LayerDeclaration;
import amidst.mojangapi.world.Dimension;
import amidst.mojangapi.world.icon.producer.WorldIconProducer;
@NotThreadSafe
public class WorldIconLoader<T> extends FragmentLoader {
private final WorldIconProducer<T> producer;
private final Function<Fragment, T> additionalDataExtractor;
public WorldIconLoader(LayerDeclaration declaration, WorldIconProducer<T> producer) {
this(declaration, producer, fragment -> null);
}
public WorldIconLoader(
LayerDeclaration declaration,
WorldIconProducer<T> producer,
Function<Fragment, T> additionalDataExtractor) {
super(declaration);
this.producer = producer;
this.additionalDataExtractor = additionalDataExtractor;
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
@Override
public void load(Dimension dimension, Fragment fragment) {
doLoad(fragment);
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
@Override
public void reload(Dimension dimension, Fragment fragment) {
doLoad(fragment);
}
@CalledOnlyBy(AmidstThread.FRAGMENT_LOADER)
private void doLoad(Fragment fragment) {
fragment.putWorldIcons(
declaration.getLayerId(),
producer.getAt(fragment.getCorner(), additionalDataExtractor.apply(fragment)));
}
}
|
amidst
|
src\main\java\amidst\gui\crash\CrashWindow.java
|
package amidst.gui.crash;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.logging.AmidstLogger;
import net.miginfocom.swing.MigLayout;
@NotThreadSafe
public enum CrashWindow {
CRASHING("Amidst crashed!", true, () -> {
System.exit(4);
}),
INTEREST("Log Messages", false, () -> {
// noop
});
public static void showAfterCrash() {
String allMessages = AmidstLogger.getAllMessages();
SwingUtilities.invokeLater(() -> CRASHING.set(allMessages));
}
public static void showForInterest() {
String allMessages = AmidstLogger.getAllMessages();
SwingUtilities.invokeLater(() -> INTEREST.set(allMessages));
}
private final JLabel pleaseReportLabel;
private final JTextField pleaseReportTextField;
private final JTextArea logMessagesTextArea;
private final JFrame frame;
private final boolean isCrashing;
private final Runnable executeOnClose;
@CalledOnlyBy(AmidstThread.EDT)
private CrashWindow(String title, boolean isCrashing, Runnable executeOnClose) {
this.isCrashing = isCrashing;
this.executeOnClose = executeOnClose;
if (isCrashing) {
this.pleaseReportLabel = new JLabel("Please report this bug on:");
this.pleaseReportTextField = createReportingTextField();
} else {
this.pleaseReportLabel = null;
this.pleaseReportTextField = null;
}
this.logMessagesTextArea = createLogMessagesTextArea();
this.frame = createFrame(title);
}
@CalledOnlyBy(AmidstThread.EDT)
private JScrollPane createLogMessagesScrollPane(JTextArea textArea) {
JScrollPane result = new JScrollPane(textArea);
result.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
result.setBorder(new LineBorder(Color.darkGray, 1));
return result;
}
@CalledOnlyBy(AmidstThread.EDT)
private JFrame createFrame(String title) {
JFrame result = new JFrame(title);
result.getContentPane().setLayout(new MigLayout());
if (isCrashing) {
result.add(pleaseReportLabel, "growx, pushx, wrap");
result.add(pleaseReportTextField, "growx, pushx, wrap");
}
result.add(createLogMessagesScrollPane(logMessagesTextArea), "grow, push");
result.setSize(800, 600);
result.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
result.setVisible(false);
executeOnClose.run();
}
});
return result;
}
@CalledOnlyBy(AmidstThread.EDT)
private JTextField createReportingTextField() {
JTextField result = new JTextField("https://github.com/toolbox4minecraft/amidst/issues/new");
result.setEditable(false);
result.selectAll();
return result;
}
@CalledOnlyBy(AmidstThread.EDT)
private JTextArea createLogMessagesTextArea() {
JTextArea result = new JTextArea();
result.setEditable(false);
result.setFont(new Font("arial", Font.PLAIN, 10));
return result;
}
@CalledOnlyBy(AmidstThread.EDT)
public void set(String logMessages) {
if (isCrashing) {
this.pleaseReportTextField.selectAll();
}
this.logMessagesTextArea.setText(logMessages);
this.frame.setVisible(true);
}
}
|
amidst
|
src\main\java\amidst\gui\export\BiomeExporter.java
|
package amidst.gui.export;
import static amidst.gui.main.viewer.widget.ProgressWidget.ProgressEntryType.MAX;
import static amidst.gui.main.viewer.widget.ProgressWidget.ProgressEntryType.MIN;
import static amidst.gui.main.viewer.widget.ProgressWidget.ProgressEntryType.PROGRESS;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.ColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferInt;
import java.awt.image.DirectColorModel;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.awt.image.SampleModel;
import java.awt.image.SinglePixelPackedSampleModel;
import java.awt.image.WritableRaster;
import java.io.IOException;
import java.nio.file.Files;
import java.util.AbstractMap;
import java.util.Map.Entry;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import javax.imageio.ImageIO;
import javax.swing.SwingUtilities;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.ThreadSafe;
import amidst.gui.main.menu.AmidstMenu;
import amidst.gui.main.viewer.widget.ProgressWidget.ProgressEntryType;
import amidst.logging.AmidstLogger;
import amidst.logging.AmidstMessageBox;
import amidst.mojangapi.world.coordinates.CoordinatesInWorld;
import amidst.mojangapi.world.coordinates.Resolution;
import amidst.mojangapi.world.oracle.BiomeDataOracle;
import amidst.settings.biomeprofile.BiomeProfileSelection;
import amidst.threading.WorkerExecutor;
import amidst.threading.worker.ProgressReporter;
@ThreadSafe
public class BiomeExporter {
private static final AtomicLong ACTIVE_THREADS = new AtomicLong(0);
private final WorkerExecutor workerExecutor;
public BiomeExporter(WorkerExecutor workerExecutor) {
this.workerExecutor = workerExecutor;
}
@CalledOnlyBy(AmidstThread.EDT)
public void export(BiomeDataOracle biomeDataOracle,
BiomeExporterConfiguration configuration,
Consumer<Entry<ProgressEntryType, Integer>> progressListener,
AmidstMenu menuBar) {
workerExecutor.<Entry<ProgressEntryType, Integer>> run((p) -> {
SwingUtilities.invokeLater(() -> {
menuBar.setMenuItemsEnabled(new String[] {
"New From Seed ...",
"New From Random Seed",
"Open Save Game ...",
"Switch Profile ...",
"Select Look & Feel"
}, false);
});
ACTIVE_THREADS.incrementAndGet();
try {
this.doExport(biomeDataOracle, configuration, p);
} finally {
ACTIVE_THREADS.decrementAndGet();
SwingUtilities.invokeLater(() -> {
menuBar.setMenuItemsEnabled(new String[] {
"Export Biomes to Image ...",
"New From Seed ...",
"New From Random Seed",
"Open Save Game ...",
"Switch Profile ...",
"Select Look & Feel",
"Biome Profile"
}, true);
});
}
}, progressListener, this::onException);
}
@CalledOnlyBy(AmidstThread.WORKER)
private void doExport(BiomeDataOracle biomeDataOracle,
BiomeExporterConfiguration configuration,
ProgressReporter<Entry<ProgressEntryType, Integer>> progressReporter) {
try {
progressReporter.report(entry(MIN, 0));
progressReporter.report(entry(PROGRESS, 0));
int resolutionFactor = Resolution.from(configuration.isQuarterResolution()).getStep();
int x = (int) configuration.getTopLeftCoord().getX();
int y = (int) configuration.getTopLeftCoord().getY();
int width = ((int) configuration.getBottomRightCoord().getX() - x) / resolutionFactor;
int height = ((int) configuration.getBottomRightCoord().getY() - y) / resolutionFactor;
progressReporter.report(entry(MAX, height + 1));
RenderedImage img = new CustomRenderedImage(x, y, width, height,
configuration.getBiomeProfileSelection(), biomeDataOracle, configuration.isQuarterResolution(),
progressReporter);
try {
ImageIO.write(img, "png", configuration.getImagePath().toAbsolutePath().toFile());
} catch (Exception e) {
AmidstLogger.error(e, "An error occured while trying to export the image");
AmidstMessageBox.displayError("Export Biome Images", e, "An error occured while trying to export the image");
} finally {
System.gc();
progressReporter.report(entry(PROGRESS, height + 1));
}
} finally {
// delete file if we made it earlier and didn't write to it or closed out early
try {
if (Files.size(configuration.getImagePath()) == 0) {
Files.delete(configuration.getImagePath());
}
} catch (IOException e) {
AmidstLogger.error("Error accessing blank file: " + configuration.getImagePath().toAbsolutePath().toString());
}
}
}
private static <K, V> Entry<K, V> entry(K key, V value) {
return new AbstractMap.SimpleImmutableEntry<K, V>(key, value);
}
private void onException(Exception e) {
AmidstLogger.error(e);
}
public static boolean isExporterRunning() {
if(ACTIVE_THREADS.get() > 0) {
return true;
}
return false;
}
private static class CustomRenderedImage implements RenderedImage {
private final static int[] BITMASKS = {
0xFF0000,
0x00FF00,
0x0000FF
};
private final static int DEFAULT_BATCH_HEIGHT = 16;
private final int worldX, worldY, width, height;
private final ColorModel colorModel;
private final SampleModel sampleModel;
private final BiomeProfileSelection biomeProfileSelection;
private final BiomeDataOracle biomeDataOracle;
private final boolean useQuarterResolution;
private final int resolutionFactor;
private final ProgressReporter<Entry<ProgressEntryType, Integer>> progressReporter;
// The PNG renderer asks for data scanline by scanline, but the BiomeDataOracle has better
// performance when computing biome data for "thicker" regions.
// So we calculate several lines at once and cache the pixels in this array.
private int[] cachedPixels;
private int cachedY;
private int cachedHeight;
public CustomRenderedImage(
int worldX,
int worldY,
int width,
int height,
BiomeProfileSelection biomeProfileSelection,
BiomeDataOracle biomeDataOracle,
boolean useQuarterResolution,
ProgressReporter<Entry<ProgressEntryType, Integer>> progressReporter) {
this.useQuarterResolution = useQuarterResolution;
this.resolutionFactor = Resolution.from(useQuarterResolution).getStep();
this.worldX = worldX;
this.worldY = worldY;
this.width = width;
this.height = height;
this.colorModel = new DirectColorModel(24, BITMASKS[0], BITMASKS[1], BITMASKS[2]);
this.sampleModel = new SinglePixelPackedSampleModel(DataBuffer.TYPE_INT, width, height, BITMASKS);
this.biomeProfileSelection = biomeProfileSelection;
this.biomeDataOracle = biomeDataOracle;
this.progressReporter = progressReporter;
this.cachedHeight = DEFAULT_BATCH_HEIGHT;
}
@Override
public ColorModel getColorModel() {
return colorModel;
}
@Override
public SampleModel getSampleModel() {
return sampleModel;
}
@Override
public int getMinX() {
return 0;
}
@Override
public int getMinY() {
return 0;
}
@Override
public int getWidth() {
return width;
}
@Override
public int getHeight() {
return height;
}
@Override
public Raster getData(Rectangle rect) {
if (rect.x != getMinX() || rect.width != getWidth() || rect.height != 1) {
throw new IllegalArgumentException("this RenderedImage only supports producing Rasters for horizontal slices");
}
if (cachedPixels == null) {
cachedPixels = new int[Math.multiplyExact(getWidth(), cachedHeight)];
cachedY = Integer.MIN_VALUE;
}
// New batch, calculate the new pixels
if (rect.y < cachedY || rect.y >= cachedY + cachedHeight) {
CoordinatesInWorld corner = CoordinatesInWorld.from((long) worldX + rect.x * resolutionFactor, (long) worldY + rect.y * resolutionFactor);
biomeDataOracle.getBiomeData(corner, getWidth(), cachedHeight, useQuarterResolution, data -> {
for (int i = 0; i < cachedPixels.length; i++) {
cachedPixels[i] = biomeProfileSelection.getBiomeColorOrUnknown(data[i]).getRGB();
}
});
cachedY = rect.y;
}
int bufSize = Math.multiplyExact(getWidth(), rect.height);
int bufOffset = Math.multiplyExact(getWidth(), rect.y - cachedY);
DataBufferInt buffer = new DataBufferInt(cachedPixels, bufSize, bufOffset);
Raster r = Raster.createPackedRaster(buffer, getWidth(), rect.height, getWidth(), BITMASKS, new Point(rect.x, rect.y));
progressReporter.report(entry(PROGRESS, rect.y));
return r;
}
@Override
public Raster getData() {
throw new UnsupportedOperationException();
}
@Override
public WritableRaster copyData(WritableRaster arg0) {
throw new UnsupportedOperationException();
}
@Override
public int getMinTileX() {
throw new UnsupportedOperationException();
}
@Override
public int getMinTileY() {
throw new UnsupportedOperationException();
}
@Override
public int getNumXTiles() {
throw new UnsupportedOperationException();
}
@Override
public int getNumYTiles() {
throw new UnsupportedOperationException();
}
@Override
public Object getProperty(String name) {
throw new UnsupportedOperationException();
}
@Override
public String[] getPropertyNames() {
throw new UnsupportedOperationException();
}
@Override
public Vector<RenderedImage> getSources() {
throw new UnsupportedOperationException();
}
@Override
public Raster getTile(int x, int y) {
throw new UnsupportedOperationException();
}
@Override
public int getTileGridXOffset() {
throw new UnsupportedOperationException();
}
@Override
public int getTileGridYOffset() {
throw new UnsupportedOperationException();
}
@Override
public int getTileHeight() {
throw new UnsupportedOperationException();
}
@Override
public int getTileWidth() {
throw new UnsupportedOperationException();
}
}
}
|
amidst
|
src\main\java\amidst\gui\export\BiomeExporterConfiguration.java
|
package amidst.gui.export;
import java.nio.file.Path;
import amidst.documentation.Immutable;
import amidst.mojangapi.world.coordinates.CoordinatesInWorld;
import amidst.settings.biomeprofile.BiomeProfileSelection;
@Immutable
public class BiomeExporterConfiguration {
private final Path imageFile;
private final boolean useQuarterResolution;
private final CoordinatesInWorld topLeftCoord;
private final CoordinatesInWorld bottomRightCoord;
private final BiomeProfileSelection biomeProfileSelection;
public BiomeExporterConfiguration(Path imageFile, boolean useQuarterResolution, CoordinatesInWorld topLeftCoord, CoordinatesInWorld bottomRightCoord, BiomeProfileSelection biomeProfileSelection) {
this.imageFile = imageFile;
this.useQuarterResolution = useQuarterResolution;
this.topLeftCoord = topLeftCoord;
this.bottomRightCoord = bottomRightCoord;
this.biomeProfileSelection = biomeProfileSelection;
}
public Path getImagePath() {
return imageFile;
}
public boolean isQuarterResolution() {
return useQuarterResolution;
}
public CoordinatesInWorld getTopLeftCoord() {
return topLeftCoord;
}
public CoordinatesInWorld getBottomRightCoord() {
return bottomRightCoord;
}
public BiomeProfileSelection getBiomeProfileSelection() {
return biomeProfileSelection;
}
}
|
amidst
|
src\main\java\amidst\gui\export\BiomeExporterDialog.java
|
package amidst.gui.export;
import static java.awt.GridBagConstraints.BOTH;
import static java.awt.GridBagConstraints.CENTER;
import static java.awt.GridBagConstraints.EAST;
import static java.awt.GridBagConstraints.HORIZONTAL;
import static java.awt.GridBagConstraints.NONE;
import static java.awt.GridBagConstraints.SOUTH;
import static java.awt.GridBagConstraints.SOUTHEAST;
import static java.awt.GridBagConstraints.SOUTHWEST;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Component;
import java.awt.Composite;
import java.awt.Frame;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.util.Collections;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Consumer;
import java.util.function.Supplier;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import amidst.documentation.NotThreadSafe;
import amidst.gui.main.Actions;
import amidst.gui.main.PNGFileFilter;
import amidst.gui.main.menu.AmidstMenu;
import amidst.gui.main.viewer.FragmentGraphToScreenTranslator;
import amidst.gui.main.viewer.widget.ProgressWidget.ProgressEntryType;
import amidst.logging.AmidstLogger;
import amidst.logging.AmidstMessageBox;
import amidst.mojangapi.minecraftinterface.MinecraftInterfaceException;
import amidst.mojangapi.world.World;
import amidst.mojangapi.world.WorldOptions;
import amidst.mojangapi.world.biome.Biome;
import amidst.mojangapi.world.biome.UnknownBiomeIdException;
import amidst.mojangapi.world.coordinates.CoordinatesInWorld;
import amidst.mojangapi.world.oracle.BiomeDataOracle;
import amidst.settings.Setting;
import amidst.settings.biomeprofile.BiomeProfileSelection;
import amidst.util.SwingUtils;
@NotThreadSafe
public class BiomeExporterDialog {
private static final int PREVIEW_SIZE = 100;
private static final ExecutorService previewUpdater = Executors.newSingleThreadExecutor(r -> new Thread(r, "BiomePreviewUpdater"));
private final Setting<String> lastBiomeExportPath;
private final BiomeExporter biomeExporter;
private final Frame parentFrame;
private final Supplier<AmidstMenu> menuBarSupplier;
private final BiomeProfileSelection biomeProfileSelection;
private final GridBagConstraints constraints;
private final GridBagConstraints labelPaneConstraints;
private final JSpinner leftSpinner, topSpinner, rightSpinner, bottomSpinner;
private final JCheckBox fullResCheckBox;
private final JTextField pathField;
private final JButton browseButton;
private final JButton exportButton;
private final BufferedImage previewImage;
private final ImageIcon previewIcon;
private final JLabel previewLabel;
private final JDialog dialog;
private WorldOptions worldOptions;
private BiomeDataOracle biomeDataOracle;
private Consumer<Entry<ProgressEntryType, Integer>> progressListener;
public BiomeExporterDialog(BiomeExporter biomeExporter, Frame parentFrame, BiomeProfileSelection biomeProfileSelection,
Supplier<AmidstMenu> menuBarSupplier, Setting<String> lastBiomeExportPath) {
// @formatter:off
this.lastBiomeExportPath = lastBiomeExportPath;
this.biomeExporter = biomeExporter;
this.parentFrame = parentFrame;
this.menuBarSupplier = menuBarSupplier;
this.biomeProfileSelection = biomeProfileSelection;
this.constraints = new GridBagConstraints();
this.labelPaneConstraints = new GridBagConstraints();
this.leftSpinner = createCoordinateSpinner();
this.topSpinner = createCoordinateSpinner();
this.rightSpinner = createCoordinateSpinner();
this.bottomSpinner = createCoordinateSpinner();
this.fullResCheckBox = createFullResCheckbox();
this.pathField = createPathField();
this.browseButton = createBrowseButton();
this.exportButton = createExportButton();
this.previewImage = new BufferedImage(PREVIEW_SIZE, PREVIEW_SIZE, BufferedImage.TYPE_INT_ARGB);
this.previewIcon = new ImageIcon(new BufferedImage(PREVIEW_SIZE * 2, PREVIEW_SIZE * 2, BufferedImage.TYPE_INT_ARGB));
this.previewLabel = createPreviewLabel();
this.dialog = createDialog();
// @formatter:on
}
private JCheckBox createFullResCheckbox() {
JCheckBox newCheckBox = new JCheckBox("Full Resolution");
newCheckBox.addChangeListener(e -> {
renderPreview();
});
return newCheckBox;
}
private JTextField createPathField() {
JTextField newTextField = new JTextField();
newTextField.setPreferredSize(new JTextField(String.join("", Collections.nCopies(50, "_"))).getPreferredSize());
return newTextField;
}
private JSpinner createCoordinateSpinner() {
JSpinner newSpinner = new JSpinner(new SpinnerNumberModel(0, -30000000, 30000000, 25));
newSpinner.addChangeListener(e -> {
renderPreview();
});
return newSpinner;
}
private JLabel createPreviewLabel() {
JLabel newLabel = new JLabel();
newLabel.setIcon(previewIcon);
newLabel.setBorder(new LineBorder(Color.BLACK, 2));
return newLabel;
}
private JButton createExportButton() {
JButton exportButton = new JButton("Export");
exportButton.addActionListener((e) -> {
try {
topSpinner.commitEdit();
leftSpinner.commitEdit();
bottomSpinner.commitEdit();
rightSpinner.commitEdit();
} catch (ParseException e1) {
// resets itself to previous value
}
CoordinatesInWorld topLeft = getTopLeftCoordinates();
CoordinatesInWorld bottomRight = getBottomRightCoordinates();
if (verifyImageCoordinates(topLeft, bottomRight) && verifyPathString(pathField.getText())) {
Path path = Paths.get(pathField.getText());
lastBiomeExportPath.set(path.toAbsolutePath().getParent().toString());
biomeExporter.export(
biomeDataOracle,
new BiomeExporterConfiguration(
path,
!fullResCheckBox.isSelected(),
topLeft,
bottomRight,
biomeProfileSelection
),
progressListener,
menuBarSupplier.get()
);
dialog.dispose();
}
});
return exportButton;
}
private boolean verifyPathString(String path) {
try {
Path p = Paths.get(path);
Files.createDirectories(p.getParent());
boolean fileExists = Files.exists(p);
if (fileExists && !Files.isRegularFile(p)) {
String message = "Unable to export to path: " + p.toString() + "\nReason: Not a file";
AmidstLogger.warn(message);
AmidstMessageBox.displayError(dialog, "Error", message);
} else if (!Actions.canWriteToFile(p)) {
String message = "Unable to export to path: " + p.toString() + "\nReason: No writing permissions";
AmidstLogger.warn(message);
AmidstMessageBox.displayError(dialog, "Error", message);
} else if (!fileExists || AmidstMessageBox.askToConfirmYesNo(dialog, "Replace file?",
"File already exists. Do you want to replace it?\n" + p.toString() + "")) {
return true;
}
return false;
} catch (InvalidPathException e) {
String message = "Unable to export to path\nReason: Invalid path given";
AmidstLogger.warn(message);
AmidstMessageBox.displayError(dialog, "Error", message);
} catch (IOException e) {
String message = "Unable to export to path\nReason: Error creating directories";
AmidstLogger.warn(message);
AmidstMessageBox.displayError(dialog, "Error", message);
}
return false;
}
public boolean verifyImageCoordinates(CoordinatesInWorld topLeft, CoordinatesInWorld bottomRight) {
if((topLeft != null && bottomRight != null) &&
(topLeft.getX() >= bottomRight.getX() || topLeft.getY() >= bottomRight.getY())) {
String message = "Unable to create image: Invalid image coordinates detected.";
AmidstLogger.warn(message);
AmidstMessageBox.displayError(dialog, "Error", message);
return false;
} else {
return true;
}
}
private JButton createBrowseButton() {
JButton newButton = new JButton("Browse...");
newButton.addActionListener(e -> {
Path exportPath = getExportPath();
if (exportPath != null) {
pathField.setText(exportPath.toAbsolutePath().toString());
}
});
return newButton;
}
private Path getExportPath() {
Path file = null;
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new PNGFileFilter());
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.setSelectedFile(Paths.get(pathField.getText()).toAbsolutePath().toFile());
if (fileChooser.showDialog(dialog, "Confirm") == JFileChooser.APPROVE_OPTION) {
file = Actions.appendFileExtensionIfNecessary(fileChooser.getSelectedFile().toPath(), "png");
}
return file;
}
private String getSuggestedFilename() {
return "biomes_" + worldOptions.getWorldType().getFilenameText() + "_" + worldOptions.getWorldSeed().getLong() + ".png";
}
private JPanel createLabeledPanel(String label, Component component, int fillConst) {
JPanel newPanel = new JPanel(new GridBagLayout());
JLabel newLabel = new JLabel(label);
newLabel.setHorizontalAlignment(SwingConstants.CENTER);
newLabel.setVerticalAlignment(SwingConstants.BOTTOM);
setLabelPaneConstraints(0, 0, 0, 0, HORIZONTAL, 0, 0, 1, 1, 1.0, 0.0, SOUTH);
newPanel.add(newLabel, labelPaneConstraints);
setLabelPaneConstraints(0, 0, 0, 0, fillConst, 0, 1, 1, 1, 1.0, 0.0, CENTER);
newPanel.add(component, labelPaneConstraints);
return newPanel;
}
private JDialog createDialog() {
JPanel panel = new JPanel(new GridBagLayout());
setConstraints(40, 0, 0, 0, NONE, 1, 1, 1, 1, 0.0, 0.0, SOUTH);
panel.add(createLabeledPanel("Top:", topSpinner, NONE), constraints);
setConstraints(20, 20, 0, 0, NONE, 0, 2, 1, 1, 0.0, 0.0, SOUTH);
panel.add(createLabeledPanel("Left:", leftSpinner, NONE), constraints);
setConstraints(20, 0, 0, 0, NONE, 1, 3, 1, 1, 0.0, 0.0, SOUTH);
panel.add(createLabeledPanel("Bottom:", bottomSpinner, NONE), constraints);
setConstraints(20, 0, 0, 0, NONE, 2, 2, 1, 1, 0.0, 0.0, SOUTH);
panel.add(createLabeledPanel("Right:", rightSpinner, NONE), constraints);
setConstraints(10, 20, 0, 0, NONE, 0, 5, 2, 1, 0.0, 0.0, SOUTHWEST);
panel.add(fullResCheckBox, constraints);
setConstraints(0, 15, 0, 15, BOTH, 3, 0, 1, 6, 1.0, 0.0, CENTER);
panel.add(Box.createGlue(), constraints);
setConstraints(0, 0, 0, 0, BOTH, 0, 4, 4, 1, 0.0, 1.0, CENTER);
panel.add(Box.createGlue(), constraints);
JPanel pathPanel = new JPanel(new GridBagLayout());
setConstraints(0, 0, 0, 0, HORIZONTAL, 0, 0, 1, 1, 0.0, 0.0, SOUTH);
pathPanel.add(createLabeledPanel("Path:", pathField, HORIZONTAL), constraints);
setConstraints(0, 10, 0, 0, HORIZONTAL, 1, 0, 1, 1, 0.0, 0.0, SOUTH);
pathPanel.add(browseButton, constraints);
setConstraints(10, 20, 20, 10, BOTH, 0, 6, 4, 2, 0.0, 0.0, SOUTHWEST);
panel.add(pathPanel, constraints);
setConstraints(15, 10, 10, 20, BOTH, 4, 0, 1, 7, 0.0, 0.0, EAST);
panel.add(createLabeledPanel("Preview:", previewLabel, NONE), constraints);
setConstraints(10, 10, 20, 20, NONE, 4, 7, 1, 1, 0.0, 0.0, SOUTHEAST);
panel.add(exportButton, constraints);
JDialog newDialog = new JDialog(parentFrame, "Export Biome Image");
newDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
newDialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
/*
* This executes only when it's closed with the x button, alt f4, etc.
* When this happens we know that the user did not press the ok button
* to continue, so we re enable the export biomes menu button.
*/
menuBarSupplier.get().setMenuItemsEnabled(new String[] { "Export Biomes to Image ...", "Biome Profile" }, true);
newDialog.dispose();
}
});
newDialog.add(panel);
newDialog.pack();
newDialog.setResizable(false);
return newDialog;
}
private Future<?> renderTask;
private void renderPreview() {
if(renderTask != null && !renderTask.isDone()) {
renderTask.cancel(true);
}
renderTask = previewUpdater.submit(() -> {
final int quarterResFactor = fullResCheckBox.isSelected() ? 1 : 4;
try {
clearImage(previewImage);
// We use a direct int array because it's much faster than calling setRGB()
int[] pixels = ((DataBufferInt) previewImage.getRaster().getDataBuffer()).getData();
CoordinatesInWorld topLeft = getTopLeftCoordinates();
CoordinatesInWorld bottomRight = getBottomRightCoordinates();
int worldWidth = (int) (bottomRight.getX() - topLeft.getX());
int worldHeight = (int) -(topLeft.getY() - bottomRight.getY());
int worldLongestSide = Math.max(worldWidth, worldHeight);
double imgToWorldFactor = worldLongestSide / (double) PREVIEW_SIZE;
int imgXOffset = (int) (((worldLongestSide - worldWidth) / 2) / imgToWorldFactor);
int imgYOffset = (int) (((worldLongestSide - worldHeight) / 2) / imgToWorldFactor);
int imgHeightWithoutBorders = previewImage.getHeight() - imgYOffset * 2;
int imgWidthWithoutBorders = previewImage.getWidth() - imgXOffset * 2;
for(int y = 0; y < imgHeightWithoutBorders; y++) {
for(int x = 0; x < imgWidthWithoutBorders; x++) {
int worldX = (int) ((x * imgToWorldFactor + topLeft.getX()) / quarterResFactor);
int worldY = (int) ((y * imgToWorldFactor + topLeft.getY()) / quarterResFactor);
int imgX = x + imgXOffset;
int imgY = y + imgYOffset;
// we use imgY instead of (previewImage.getHeight() - imgY - 1) to mirror the y axis
int imgidx = imgY * previewImage.getWidth() + imgX;
Biome biome = biomeDataOracle.getBiomeAt(worldX, worldY, !fullResCheckBox.isSelected());
pixels[imgidx] = biomeProfileSelection.getBiomeColorOrUnknown(biome.getId()).getRGB();
}
}
previewIcon.setImage(previewImage.getScaledInstance(previewIcon.getIconWidth(), previewIcon.getIconHeight(), Image.SCALE_FAST));
SwingUtilities.invokeLater(() -> previewLabel.repaint());
} catch(MinecraftInterfaceException | UnknownBiomeIdException e) {
AmidstLogger.error(e);
}
});
}
private void clearImage(BufferedImage img) {
Graphics2D graphics = (Graphics2D) img.getGraphics();
Composite tempComposite = graphics.getComposite();
graphics.setComposite(AlphaComposite.Clear);
graphics.fillRect(0, 0, img.getWidth(), img.getHeight());
graphics.setComposite(tempComposite);
}
public void createAndShow(World world, FragmentGraphToScreenTranslator translator,
Consumer<Entry<ProgressEntryType, Integer>> progressListener) {
menuBarSupplier.get().setMenuItemsEnabled(new String[] { "Export Biomes to Image ...", "Biome Profile" }, false);
this.worldOptions = world.getWorldOptions();
this.biomeDataOracle = world.getOverworldBiomeDataOracle();
this.progressListener = progressListener;
CoordinatesInWorld defaultTopLeft = translator.screenToWorld(new Point(0, 0));
CoordinatesInWorld defaultBottomRight = translator
.screenToWorld(new Point((int) translator.getWidth(), (int) translator.getHeight()));
leftSpinner.setValue(defaultTopLeft.getX());
topSpinner.setValue(defaultTopLeft.getY());
rightSpinner.setValue(defaultBottomRight.getX());
bottomSpinner.setValue(defaultBottomRight.getY());
pathField.setText(Paths.get(lastBiomeExportPath.get(), getSuggestedFilename()).toAbsolutePath().toString());
renderPreview();
dialog.setVisible(true);
}
public void dispose() {
menuBarSupplier.get().setMenuItemsEnabled(new String[] { "Export Biomes to Image ...", "Biome Profile" }, true);
SwingUtils.destroyComponentTree(dialog);
}
public void softDispose() {
menuBarSupplier.get().setMenuItemsEnabled(new String[] { "Export Biomes to Image ...", "Biome Profile" }, true);
dialog.dispose();
}
private CoordinatesInWorld getTopLeftCoordinates() {
return new CoordinatesInWorld(((Number) leftSpinner.getValue()).longValue(), ((Number) topSpinner.getValue()).longValue());
}
private CoordinatesInWorld getBottomRightCoordinates() {
return new CoordinatesInWorld(((Number) rightSpinner.getValue()).longValue(), ((Number) bottomSpinner.getValue()).longValue());
}
private void setConstraints(int iTop, int iLeft, int iBottom, int iRight, int fillConst, int gridx,
int gridy, int gridw, int gridh, double weightx, double weighty, int anchor) {
constraints.insets = new Insets(iTop, iLeft, iBottom, iRight);
constraints.fill = fillConst;
constraints.gridx = gridx;
constraints.gridy = gridy;
constraints.gridwidth = gridw;
constraints.gridheight = gridh;
constraints.weightx = weightx;
constraints.weighty = weighty;
constraints.anchor = anchor;
}
private void setLabelPaneConstraints(int iTop, int iLeft, int iBottom, int iRight, int fillConst, int gridx,
int gridy, int gridw, int gridh, double weightx, double weighty, int anchor) {
labelPaneConstraints.insets = new Insets(iTop, iLeft, iBottom, iRight);
labelPaneConstraints.fill = fillConst;
labelPaneConstraints.gridx = gridx;
labelPaneConstraints.gridy = gridy;
labelPaneConstraints.gridwidth = gridw;
labelPaneConstraints.gridheight = gridh;
labelPaneConstraints.weightx = weightx;
labelPaneConstraints.weighty = weighty;
labelPaneConstraints.anchor = anchor;
}
}
|
amidst
|
src\main\java\amidst\gui\export\BiomeExportException.java
|
package amidst.gui.export;
public class BiomeExportException extends Exception {
private static final long serialVersionUID = 8652575123411388901L;
public BiomeExportException() {
super();
}
public BiomeExportException(String message) {
super(message);
}
}
|
amidst
|
src\main\java\amidst\gui\license\License.java
|
package amidst.gui.license;
import java.io.IOException;
import amidst.ResourceLoader;
import amidst.documentation.Immutable;
import amidst.logging.AmidstLogger;
@Immutable
public class License {
private final String name;
private final String licenseText;
public License(String name, String path) {
this.name = name;
this.licenseText = readLicenseText(path);
}
public String readLicenseText(String path) {
try {
return ResourceLoader.getResourceAsString(path);
} catch (IOException e) {
AmidstLogger.warn(e, "Unable to read license for '{}' at '{}'.", name, path);
return "License text is missing.";
}
}
public String getName() {
return name;
}
public String getLicenseText() {
return licenseText;
}
@Override
public String toString() {
return name;
}
}
|
amidst
|
src\main\java\amidst\gui\license\LicenseWindow.java
|
package amidst.gui.license;
import amidst.documentation.Immutable;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.Color;
import java.awt.Container;
import java.util.Arrays;
import java.util.List;
import static amidst.Amidst.BUFFERED_IMAGES;
@Immutable
public class LicenseWindow {
private static final String LICENSES_DIRECTORY = "/amidst/gui/license/";
public LicenseWindow() {
License[] licenses = createLicenses();
JTextArea textArea = createLicenseTextArea();
JScrollPane scrollPane = createScrollPane(textArea);
JList<License> licenseList = createLicenseList(licenses, textArea);
createFrame(licenseList, scrollPane);
}
private License[] createLicenses() {
List<License> result = Arrays.asList(
createLicense("Amidst", "amidst.txt"),
createLicense("Args4j", "args4j.txt"),
createLicense("Gson", "gson.txt"),
createLicense("MiG Layout", "miglayout.txt"),
createLicense("Querz-NBT", "querz-nbt.txt"));
return result.toArray(new License[result.size()]);
}
private License createLicense(String name, String path) {
return new License(name, LICENSES_DIRECTORY + path);
}
private JTextArea createLicenseTextArea() {
JTextArea result = new JTextArea();
result.setEditable(false);
result.setLineWrap(true);
result.setWrapStyleWord(true);
return result;
}
private JScrollPane createScrollPane(JTextArea textArea) {
JScrollPane result = new JScrollPane(textArea);
result.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
return result;
}
private JList<License> createLicenseList(License[] licenses, final JTextArea textArea) {
final JList<License> result = new JList<>(licenses);
result.setBorder(new LineBorder(Color.darkGray, 1));
result.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
result.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
textArea.setText(result.getSelectedValue().getLicenseText());
textArea.setCaretPosition(0);
}
});
result.setSelectedIndex(0);
return result;
}
private JFrame createFrame(JList<License> licenseList, JScrollPane scrollPane) {
JFrame frame = new JFrame("Licenses");
initContentPane(frame.getContentPane(), licenseList, scrollPane);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setIconImages(BUFFERED_IMAGES);
frame.setSize(870, 550);
frame.setVisible(true);
return frame;
}
private void initContentPane(Container contentPane, JList<License> licenseList, JScrollPane scrollPane) {
contentPane.setLayout(new MigLayout());
contentPane.add(licenseList, "w 150!, h 0:2400:2400");
contentPane.add(scrollPane, "w 0:4800:4800, h 0:2400:2400");
}
}
|
amidst
|
src\main\java\amidst\gui\main\Actions.java
|
package amidst.gui.main;
import amidst.Application;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledByAny;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.gui.crash.CrashWindow;
import amidst.gui.export.BiomeExporter;
import amidst.gui.export.BiomeExporterDialog;
import amidst.gui.main.menu.MovePlayerPopupMenu;
import amidst.gui.main.viewer.ViewerFacade;
import amidst.gui.seedsearcher.SeedSearcherWindow;
import amidst.logging.AmidstLogger;
import amidst.mojangapi.world.WorldOptions;
import amidst.mojangapi.world.WorldSeed;
import amidst.mojangapi.world.WorldType;
import amidst.mojangapi.world.coordinates.CoordinatesInWorld;
import amidst.mojangapi.world.icon.WorldIcon;
import amidst.mojangapi.world.player.Player;
import amidst.mojangapi.world.player.PlayerCoordinates;
import amidst.settings.Setting;
import amidst.settings.biomeprofile.BiomeProfile;
import amidst.settings.biomeprofile.BiomeProfileDirectory;
import amidst.settings.biomeprofile.BiomeProfileSelection;
import amidst.util.FileExtensionChecker;
import javax.imageio.ImageIO;
import java.awt.Component;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
@NotThreadSafe
public class Actions {
/**
* A reference to the Amidst instance.
*/
private final Application application;
private final MainWindowDialogs dialogs;
private final WorldSwitcher worldSwitcher;
private final SeedSearcherWindow seedSearcherWindow;
private final BiomeExporterDialog biomeExporterDialog;
private final BiomeProfileSelection biomeProfileSelection;
private final Setting<String> lastScreenshotPath;
/**
* A reference to the main window.
*/
private final MainWindow mainWindow;
@CalledOnlyBy(AmidstThread.EDT)
public Actions(
Application application,
MainWindowDialogs dialogs,
WorldSwitcher worldSwitcher,
SeedSearcherWindow seedSearcherWindow,
BiomeExporterDialog biomeExporterDialog,
MainWindow mainWindow,
BiomeProfileSelection biomeProfileSelection,
Setting<String> lastScreenshotPath) {
this.application = application;
this.dialogs = dialogs;
this.worldSwitcher = worldSwitcher;
this.seedSearcherWindow = seedSearcherWindow;
this.biomeExporterDialog = biomeExporterDialog;
this.mainWindow = mainWindow;
this.biomeProfileSelection = biomeProfileSelection;
this.lastScreenshotPath = lastScreenshotPath;
}
@CalledOnlyBy(AmidstThread.EDT)
public void newFromSeed() {
WorldSeed seed = dialogs.askForSeed();
if (seed != null) {
newFromSeed(seed);
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void newFromRandom() {
biomeExporterDialog.softDispose();
newFromSeed(WorldSeed.random());
}
@CalledOnlyBy(AmidstThread.EDT)
private void newFromSeed(WorldSeed worldSeed) {
WorldType worldType = dialogs.askForWorldType();
if (worldType != null) {
biomeExporterDialog.softDispose();
worldSwitcher.displayWorld(new WorldOptions(worldSeed, worldType));
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void searchForRandom() {
seedSearcherWindow.show();
}
@CalledOnlyBy(AmidstThread.EDT)
public void openSaveGame() {
Path file = dialogs.askForSaveGame();
if (file != null) {
biomeExporterDialog.softDispose();
worldSwitcher.displayWorld(file);
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void openExportDialog() {
ViewerFacade viewerFacade = mainWindow.getViewerFacade();
if (viewerFacade != null) {
viewerFacade.openExportDialog();
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void switchProfile() {
application.displayProfileSelectWindow();
}
@CalledOnlyBy(AmidstThread.EDT)
public void exit() {
if (BiomeExporter.isExporterRunning()) {
if (dialogs.askToConfirmYesNo("Continue?", "A biome image is still exporting. Are you sure you want to continue?")) {
application.exitGracefully();
}
} else {
application.exitGracefully();
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void goToCoordinate() {
ViewerFacade viewerFacade = mainWindow.getViewerFacade();
if (viewerFacade != null) {
String input = dialogs.askForCoordinates();
if (input != null) {
CoordinatesInWorld coordinates = CoordinatesInWorld.tryParse(input);
if (coordinates != null) {
viewerFacade.centerOn(coordinates);
} else {
AmidstLogger.warn("Invalid location entered, ignoring.");
dialogs.displayError("You entered an invalid location.");
}
}
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void goToSpawn() {
ViewerFacade viewerFacade = mainWindow.getViewerFacade();
if (viewerFacade != null) {
viewerFacade.centerOn(viewerFacade.getSpawnWorldIcon());
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void goToStronghold() {
ViewerFacade viewerFacade = mainWindow.getViewerFacade();
if (viewerFacade != null) {
WorldIcon stronghold = dialogs
.askForOptions("Go to", "Select Stronghold:", viewerFacade.getStrongholdWorldIcons());
if (stronghold != null) {
viewerFacade.centerOn(stronghold);
}
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void goToPlayer() {
ViewerFacade viewerFacade = mainWindow.getViewerFacade();
if (viewerFacade != null) {
List<WorldIcon> playerWorldIcons = viewerFacade.getPlayerWorldIcons();
if (!playerWorldIcons.isEmpty()) {
WorldIcon player = dialogs.askForOptions("Go to", "Select player:", playerWorldIcons);
if (player != null) {
viewerFacade.centerOn(player);
}
} else {
AmidstLogger.warn("There are no players in this world.");
dialogs.displayError("There are no players in this world.");
}
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void zoomIn() {
adjustZoom(-4);
}
@CalledOnlyBy(AmidstThread.EDT)
public void zoomOut() {
adjustZoom(4);
}
@CalledOnlyBy(AmidstThread.EDT)
public void savePlayerLocations() {
ViewerFacade viewerFacade = mainWindow.getViewerFacade();
if (viewerFacade != null) {
if (dialogs.askToConfirmSaveGameManipulation()) {
viewerFacade.savePlayerLocations();
}
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void reloadPlayerLocations() {
ViewerFacade viewerFacade = mainWindow.getViewerFacade();
if (viewerFacade != null) {
viewerFacade.loadPlayers();
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void howCanIMoveAPlayer() {
dialogs.displayInfo(
"How can I move a player?",
"If you load the world from a save game, you can change the player locations.\n"
+ "1. Scroll the map to and right-click on the new player location, this opens a popup menu.\n"
+ "2. Select the player you want to move to the new location.\n"
+ "3. Enter the new player height (y-coordinate).\n" + "4. Save player locations.");
}
@CalledOnlyBy(AmidstThread.EDT)
public void copySeedToClipboard() {
ViewerFacade viewerFacade = mainWindow.getViewerFacade();
if (viewerFacade != null) {
String seed = "" + viewerFacade.getWorldOptions().getWorldSeed().getLong();
StringSelection selection = new StringSelection(seed);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void takeScreenshot() {
ViewerFacade viewerFacade = mainWindow.getViewerFacade();
if (viewerFacade != null) {
WorldOptions worldOptions = viewerFacade.getWorldOptions();
BufferedImage image = viewerFacade.createScreenshot();
String suggestedFilename = "screenshot_" + worldOptions.getWorldType().getFilenameText() + "_"
+ worldOptions.getWorldSeed().getLong() + ".png";
String suggestedFile = Paths.get(lastScreenshotPath.get(), suggestedFilename).toString();
Path file = dialogs.askForPNGSaveFile(suggestedFile);
if (file != null) {
file = appendFileExtensionIfNecessary(file, "png");
boolean fileExists = Files.exists(file);
if (fileExists && !Files.isRegularFile(file)) {
String message = "Unable to write screenshot, because the target exists but is not a file: "
+ file.toString();
AmidstLogger.warn(message);
dialogs.displayError(message);
} else if (!canWriteToFile(file)) {
String message = "Unable to write screenshot, because you have no writing permissions: "
+ file.toString();
AmidstLogger.warn(message);
dialogs.displayError(message);
} else if (!fileExists || dialogs.askToConfirmYesNo(
"Replace file?",
"File already exists. Do you want to replace it?\n" + file.toString() + "")) {
lastScreenshotPath.set(file.toAbsolutePath().getParent().toString());
saveImageToFile(image, file);
}
}
image.flush();
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void selectBiomeProfile(BiomeProfile profile) {
biomeProfileSelection.set(profile);
ViewerFacade viewerFacade = mainWindow.getViewerFacade();
if (viewerFacade != null) {
viewerFacade.reloadBackgroundLayer();
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void createExampleProfile(BiomeProfileDirectory dir) {
if (!dir.isValid()) {
dialogs.displayError("Unable to find biome profile directory.");
} else {
Path path = dir.getRoot().resolve("example.json");
if (BiomeProfile.createExampleProfile().save(path)) {
dialogs.displayInfo("Amidst", "Example biome profile created at:\n" + path.toAbsolutePath().toString());
} else {
dialogs.displayError("Error creating example biome profile.");
}
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void displayLogMessages() {
CrashWindow.showForInterest();
}
@CalledOnlyBy(AmidstThread.EDT)
public void checkForUpdates() {
application.checkForUpdates(dialogs);
}
@CalledOnlyBy(AmidstThread.EDT)
public void viewLicense() {
application.displayLicenseWindow();
}
@CalledOnlyBy(AmidstThread.EDT)
public void about() {
dialogs.displayInfo(
"About",
"Amidst - Advanced Minecraft Interfacing and Data/Structure Tracking\n\n"
+ "Author: Skidoodle aka skiphs\n" + "Mail: toolbox4minecraft+amidst@outlook.com\n"
+ "Project Page: https://github.com/toolbox4minecraft/amidst");
}
@CalledOnlyBy(AmidstThread.EDT)
private void adjustZoom(int notches) {
ViewerFacade viewerFacade = mainWindow.getViewerFacade();
if (viewerFacade != null) {
viewerFacade.adjustZoom(notches);
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void adjustZoom(Point mousePosition, int notches) {
ViewerFacade viewerFacade = mainWindow.getViewerFacade();
if (viewerFacade != null) {
viewerFacade.adjustZoom(mousePosition, notches);
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void selectWorldIcon(WorldIcon worldIcon) {
ViewerFacade viewerFacade = mainWindow.getViewerFacade();
if (viewerFacade != null) {
viewerFacade.selectWorldIcon(worldIcon);
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void showPlayerPopupMenu(CoordinatesInWorld targetCoordinates, Component component, int x, int y) {
ViewerFacade viewerFacade = mainWindow.getViewerFacade();
if (viewerFacade != null) {
if (viewerFacade.canSavePlayerLocations()) {
new MovePlayerPopupMenu(this, viewerFacade.getMovablePlayerList(), targetCoordinates)
.show(component, x, y);
}
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void movePlayer(Player player, CoordinatesInWorld targetCoordinates) {
ViewerFacade viewerFacade = mainWindow.getViewerFacade();
if (viewerFacade != null) {
PlayerCoordinates currentCoordinates = player.getPlayerCoordinates();
long currentHeight = currentCoordinates.getY();
String input = dialogs.askForPlayerHeight(currentHeight);
if (input != null) {
player.moveTo(targetCoordinates, tryParseLong(input, currentHeight), currentCoordinates.getDimension());
viewerFacade.reloadPlayerLayer();
if (dialogs.askToConfirmYesNo("Save Player Locations", "Do you want to save the player locations?")) {
if (dialogs.askToConfirmSaveGameManipulation()) {
viewerFacade.savePlayerLocations();
}
}
}
}
}
@CalledOnlyBy(AmidstThread.EDT)
public boolean tryChangeLookAndFeel(AmidstLookAndFeel lookAndFeel) {
if (dialogs.askToConfirmYesNo("Changing Look & Feel",
"Changing the look & feel will reload Amidst. Do you want to continue?")) {
if (lookAndFeel.tryApply()) {
application.restart();
return true;
} else {
dialogs.displayError("An error occured while trying to switch to " + lookAndFeel);
}
}
return false;
}
@CalledOnlyBy(AmidstThread.EDT)
public void tryChangeThreads() {
if (dialogs.askToConfirmYesNo("Change Threads",
"This setting does not take effect until you restart the program. Restart now?")) {
application.restart();
}
}
@CalledByAny
public static long tryParseLong(String text, long defaultValue) {
try {
return Long.parseLong(text);
} catch (NumberFormatException e) {
return defaultValue;
}
}
@CalledByAny
public static boolean canWriteToFile(Path file) {
Path parent = file.getParent();
return Files.isWritable(file) || (!Files.exists(file) && parent != null && Files.isWritable(parent));
}
@CalledOnlyBy(AmidstThread.EDT)
private void saveImageToFile(BufferedImage image, Path file) {
try {
ImageIO.write(image, "png", new BufferedOutputStream(Files.newOutputStream(file)));
} catch (IOException e) {
AmidstLogger.warn(e);
dialogs.displayError(e);
}
}
@CalledByAny
public static Path appendFileExtensionIfNecessary(Path file, String fileExtension) {
String filename = file.toAbsolutePath().toString();
if (!FileExtensionChecker.hasFileExtension(filename, fileExtension)) {
filename += '.' + fileExtension;
}
return Paths.get(filename);
}
}
|
amidst
|
src\main\java\amidst\gui\main\AmidstLookAndFeel.java
|
package amidst.gui.main;
import javax.swing.LookAndFeel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import amidst.logging.AmidstLogger;
import amidst.util.OperatingSystemDetector;
public enum AmidstLookAndFeel {
DEFAULT("Default Look & Feel", UIManager.getCrossPlatformLookAndFeelClassName()),
SYSTEM("System Look & Feel", UIManager.getSystemLookAndFeelClassName());
private final String displayName;
private final String lookAndFeelClassName;
private AmidstLookAndFeel(String displayName, String lookAndFeelClassName) {
this.displayName = displayName;
this.lookAndFeelClassName = lookAndFeelClassName;
}
public boolean isCurrent() {
return lookAndFeelClassName.equals(getCurrent());
}
private static String getCurrent() {
LookAndFeel lookAndFeel = UIManager.getLookAndFeel();
if (lookAndFeel == null) {
return null;
}
return lookAndFeel.getClass().getName();
}
public String getDisplayName() {
return displayName;
}
public boolean tryApply() {
String currentLookAndFeel = getCurrent();
boolean success = true;
try {
UIManager.setLookAndFeel(lookAndFeelClassName);
AmidstLogger.info("Using look & feel: " + lookAndFeelClassName);
} catch(ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
AmidstLogger.error(e, "Couldn't apply look & feel: " + lookAndFeelClassName +
"; falling back to: " + currentLookAndFeel);
success = false;
}
if (OperatingSystemDetector.isMac()) {
OsXWorkarounds.applyWorkarounds();
}
return success;
}
@Override
public String toString() {
return getDisplayName();
}
}
|
amidst
|
src\main\java\amidst\gui\main\LevelFileFilter.java
|
package amidst.gui.main;
import java.io.File;
import javax.swing.filechooser.FileFilter;
import amidst.documentation.NotThreadSafe;
@NotThreadSafe
public class LevelFileFilter extends FileFilter {
private static final String LEVEL_DAT = "level.dat";
@Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
} else {
return file.getName().equalsIgnoreCase(LEVEL_DAT);
}
}
@Override
public String getDescription() {
return "Minecraft Data File (level.dat)";
}
}
|
amidst
|
src\main\java\amidst\gui\main\MainWindow.java
|
package amidst.gui.main;
import amidst.Amidst;
import amidst.AmidstSettings;
import amidst.Application;
import amidst.FeatureToggles;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.fragment.FragmentManager;
import amidst.fragment.layer.LayerBuilder;
import amidst.gui.export.BiomeExporter;
import amidst.gui.export.BiomeExporterDialog;
import amidst.gui.main.menu.AmidstMenu;
import amidst.gui.main.menu.AmidstMenuBuilder;
import amidst.gui.main.viewer.BiomeSelection;
import amidst.gui.main.viewer.ViewerFacade;
import amidst.gui.main.viewer.Zoom;
import amidst.gui.seedsearcher.SeedSearcher;
import amidst.gui.seedsearcher.SeedSearcherWindow;
import amidst.logging.AmidstLogger;
import amidst.mojangapi.RunningLauncherProfile;
import amidst.mojangapi.file.MinecraftInstallation;
import amidst.settings.biomeprofile.BiomeProfileDirectory;
import amidst.threading.ThreadMaster;
import amidst.util.SwingUtils;
import javax.swing.JFrame;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import static amidst.Amidst.BUFFERED_IMAGES;
/**
* The main application window, showing the world map.
*/
@NotThreadSafe
public class MainWindow {
/**
* The default window size.
*/
private static final Dimension WINDOW_DIMENSIONS = new Dimension(1000, 800);
/**
* The main window frame.
*/
private final JFrame frame;
private final WorldSwitcher worldSwitcher;
private final SeedSearcherWindow seedSearcherWindow;
private final BiomeExporterDialog biomeExporterDialog;
private final Actions actions;
private final AmidstMenu menuBar;
private ViewerFacade viewerFacade;
/**
* Creates and shows the main application window.
*
* @param application a reference to the Amidst instance
* @param settings user settings
* @param minecraftInstallation
* @param runningLauncherProfile
* @param biomeProfileDirectory
* @param zoom
* @param layerBuilder
* @param fragmentManager
* @param biomeSelection
* @param threadMaster
*/
@CalledOnlyBy(AmidstThread.EDT)
public MainWindow(Application application,
AmidstSettings settings,
MinecraftInstallation minecraftInstallation,
RunningLauncherProfile runningLauncherProfile,
BiomeProfileDirectory biomeProfileDirectory,
Zoom zoom,
LayerBuilder layerBuilder,
FragmentManager fragmentManager,
BiomeSelection biomeSelection,
ThreadMaster threadMaster) {
frame = new JFrame();
Container contentPane = frame.getContentPane();
MainWindowDialogs dialogs = new MainWindowDialogs(settings, runningLauncherProfile, frame);
if (FeatureToggles.SEED_SEARCH) {
SeedSearcher seedSearcher = new SeedSearcher(
dialogs,
runningLauncherProfile.createSilentPlayerlessCopy(),
threadMaster.getWorkerExecutor());
seedSearcherWindow = new SeedSearcherWindow(dialogs, worldSwitcher, seedSearcher);
} else {
seedSearcherWindow = null;
}
biomeExporterDialog = new BiomeExporterDialog(new BiomeExporter(threadMaster.getWorkerExecutor()), frame, settings.biomeProfileSelection, this::getMenuBar, settings.lastBiomeExportPath);
worldSwitcher = new WorldSwitcher(
minecraftInstallation,
runningLauncherProfile,
settings,
zoom,
layerBuilder,
fragmentManager,
biomeSelection,
biomeExporterDialog,
threadMaster,
frame,
contentPane,
this,
dialogs);
actions = new Actions(
application,
dialogs,
worldSwitcher,
seedSearcherWindow,
biomeExporterDialog,
this,
settings.biomeProfileSelection,
settings.lastBiomeExportPath);
menuBar = new AmidstMenuBuilder(settings, actions, biomeProfileDirectory).construct();
frame.setSize(WINDOW_DIMENSIONS);
frame.setIconImages(BUFFERED_IMAGES);
frame.setTitle(createVersionString(runningLauncherProfile));
frame.setJMenuBar(menuBar.getMenuBar());
frame.getContentPane().setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
actions.exit();
}
});
frame.setLocationRelativeTo(null);
frame.setVisible(true);
worldSwitcher.clearWorld();
runningLauncherProfile.getInitialWorldOptions().ifPresent(options -> {
AmidstLogger.info("Setting initial world options to [" + options.getWorldSeed().getLabel() + ", World Type: " + options.getWorldType() + "]");
worldSwitcher.displayWorld(options);
});
}
public WorldSwitcher getWorldSwitcher() {
return worldSwitcher;
}
public ViewerFacade getViewerFacade() {
return viewerFacade;
}
public void setViewerFacade(ViewerFacade viewerFacade) {
this.viewerFacade = viewerFacade;
}
public Actions getActions() {
return actions;
}
public AmidstMenu getMenuBar() {
return menuBar;
}
/**
* Disposes of the biome exporter, world switcher, seed searcher,
* and the main window frame.
*/
@CalledOnlyBy(AmidstThread.EDT)
public void dispose() {
biomeExporterDialog.dispose();
worldSwitcher.clearWorld();
if (FeatureToggles.SEED_SEARCH) {
seedSearcherWindow.dispose();
}
SwingUtils.destroyComponentTree(frame);
}
/**
* Gets a formatted string for the main window title.
*
* @param runningLauncherProfile the current profile
* @return a string for the title of the application
*/
@CalledOnlyBy(AmidstThread.EDT)
private static String createVersionString(RunningLauncherProfile runningLauncherProfile) {
return Amidst.VERSION.createLongVersionString() +
" - Selected Profile: " +
runningLauncherProfile.getLauncherProfile().getProfileName() +
" - Minecraft Version " +
runningLauncherProfile.getLauncherProfile().getVersionName() +
" (recognised: " +
runningLauncherProfile.getRecognisedVersion().getName() +
")";
}
}
|
amidst
|
src\main\java\amidst\gui\main\MainWindowDialogs.java
|
package amidst.gui.main;
import java.nio.file.Path;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import amidst.AmidstSettings;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.logging.AmidstMessageBox;
import amidst.mojangapi.RunningLauncherProfile;
import amidst.mojangapi.world.WorldSeed;
import amidst.mojangapi.world.WorldType;
import amidst.mojangapi.world.player.WorldPlayerType;
@NotThreadSafe
public class MainWindowDialogs {
private final AmidstSettings settings;
private final RunningLauncherProfile runningLauncherProfile;
private final JFrame frame;
@CalledOnlyBy(AmidstThread.EDT)
public MainWindowDialogs(AmidstSettings settings, RunningLauncherProfile runningLauncherProfile, JFrame frame) {
this.settings = settings;
this.runningLauncherProfile = runningLauncherProfile;
this.frame = frame;
}
@CalledOnlyBy(AmidstThread.EDT)
public WorldPlayerType askForWorldPlayerType() {
return askForOptions(
"Loading World",
"This world contains Multiplayer and Singleplayer data. What do you want to load?\n"
+ "If you do not know what to do, just choose Singleplayer.",
WorldPlayerType.getSelectable());
}
@CalledOnlyBy(AmidstThread.EDT)
public WorldSeed askForSeed() {
return new SeedPrompt(frame).askForSeed();
}
@CalledOnlyBy(AmidstThread.EDT)
public Path askForSaveGame() {
return showOpenDialogAndGetSelectedFileOrNull(createSaveGameFileChooser());
}
@CalledOnlyBy(AmidstThread.EDT)
private JFileChooser createSaveGameFileChooser() {
JFileChooser result = new JFileChooser(runningLauncherProfile.getLauncherProfile().getSaves().toFile());
result.setFileFilter(new LevelFileFilter());
result.setAcceptAllFileFilterUsed(false);
result.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
result.setFileHidingEnabled(false);
return result;
}
@CalledOnlyBy(AmidstThread.EDT)
private Path showOpenDialogAndGetSelectedFileOrNull(JFileChooser fileChooser) {
if (fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
return fileChooser.getSelectedFile().toPath();
} else {
return null;
}
}
@CalledOnlyBy(AmidstThread.EDT)
public Path askForPNGSaveFile(String suggestedFilename) {
return showSaveDialogAndGetSelectedFileOrNull(createPNGSaveFileChooser(suggestedFilename));
}
@CalledOnlyBy(AmidstThread.EDT)
private JFileChooser createPNGSaveFileChooser(String suggestedFilename) {
JFileChooser result = new JFileChooser();
result.setFileFilter(new PNGFileFilter());
result.setAcceptAllFileFilterUsed(false);
result.setSelectedFile(new java.io.File(suggestedFilename));
return result;
}
@CalledOnlyBy(AmidstThread.EDT)
private Path showSaveDialogAndGetSelectedFileOrNull(JFileChooser fileChooser) {
if (fileChooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
return fileChooser.getSelectedFile().toPath();
} else {
return null;
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void displayInfo(String title, String message) {
AmidstMessageBox.displayInfo(frame, title, message);
}
@CalledOnlyBy(AmidstThread.EDT)
public void displayError(String message) {
AmidstMessageBox.displayError(frame, "Error", message);
}
@CalledOnlyBy(AmidstThread.EDT)
public void displayError(Exception e) {
AmidstMessageBox.displayError(frame, "Error", e);
}
@CalledOnlyBy(AmidstThread.EDT)
public void displayWarning(String message) {
AmidstMessageBox.displayWarning(frame, "Warning", message);
}
@CalledOnlyBy(AmidstThread.EDT)
public boolean askToConfirmSaveGameManipulation() {
return askToConfirmYesNo(
"Save Game Manipulation",
"WARNING: You are about to change the contents of the save game directory. There is a chance that it gets corrupted.\n"
+ "We try to minimize the risk by creating a backup of the changed file, before it is changed.\n"
+ "If the backup fails, we will not write the changes.\n"
+ "You can find the backup files in the directory 'amidst/backup', which is placed in the save game directory.\n"
+ "Especially, make sure to not have the save game loaded in Minecraft during this process.\n\n"
+ "Do you want to proceed?");
}
@CalledOnlyBy(AmidstThread.EDT)
public boolean askToConfirmYesNo(String title, String message) {
return AmidstMessageBox.askToConfirmYesNo(frame, title, message);
}
@CalledOnlyBy(AmidstThread.EDT)
public WorldType askForWorldType() {
String worldTypeSetting = settings.worldType.get();
if (worldTypeSetting.equals(WorldType.PROMPT_EACH_TIME)) {
return askForOptions("World Type", "Enter world type\n", WorldType.getSelectable());
} else {
return WorldType.from(worldTypeSetting);
}
}
@CalledOnlyBy(AmidstThread.EDT)
@SuppressWarnings("unchecked")
public <T> T askForOptions(String title, String message, List<T> choices) {
Object[] choicesArray = choices.toArray();
return (T) JOptionPane
.showInputDialog(frame, message, title, JOptionPane.PLAIN_MESSAGE, null, choicesArray, choicesArray[0]);
}
@CalledOnlyBy(AmidstThread.EDT)
public String askForCoordinates() {
return askForString("Go To", "Enter coordinates: (Ex. 123,456)");
}
@CalledOnlyBy(AmidstThread.EDT)
public String askForPlayerHeight(long currentHeight) {
Object input = JOptionPane.showInputDialog(
frame,
"Enter new player height:",
"Move Player",
JOptionPane.QUESTION_MESSAGE,
null,
null,
currentHeight);
if (input != null) {
return input.toString();
} else {
return null;
}
}
@CalledOnlyBy(AmidstThread.EDT)
private String askForString(String title, String message) {
return JOptionPane.showInputDialog(frame, message, title, JOptionPane.QUESTION_MESSAGE);
}
}
|
amidst
|
src\main\java\amidst\gui\main\OsXWorkarounds.java
|
package amidst.gui.main;
import javax.swing.InputMap;
import javax.swing.UIManager;
import javax.swing.text.DefaultEditorKit;
import amidst.gui.main.menu.MenuShortcuts;
public enum OsXWorkarounds {
;
public static void applyWorkarounds() {
menuProperties();
textActions();
}
private static void menuProperties() {
System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty("com.apple.macos.useScreenMenuBar", "true");
}
// Text actions aren't properly set on the default L&F; fix this.
private static void textActions() {
// Text actions aren't properly set on the default L&F; fix this
textActionsFor("TextArea.focusInputMap");
textActionsFor("TextField.focusInputMap");
textActionsFor("TextPane.focusInputMap");
}
private static void textActionsFor(String inputMapName) {
InputMap im = (InputMap) UIManager.get(inputMapName);
im.put(MenuShortcuts.getKeyStroke("menu C"), DefaultEditorKit.copyAction);
im.put(MenuShortcuts.getKeyStroke("menu V"), DefaultEditorKit.pasteAction);
im.put(MenuShortcuts.getKeyStroke("menu X"), DefaultEditorKit.cutAction);
im.put(MenuShortcuts.getKeyStroke("menu A"), DefaultEditorKit.selectAllAction);
}
}
|
amidst
|
src\main\java\amidst\gui\main\PNGFileFilter.java
|
package amidst.gui.main;
import java.io.File;
import javax.swing.filechooser.FileFilter;
import amidst.documentation.NotThreadSafe;
import amidst.util.FileExtensionChecker;
@NotThreadSafe
public class PNGFileFilter extends FileFilter {
@Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
} else {
return FileExtensionChecker.hasFileExtension(file.getName(), "png");
}
}
@Override
public String getDescription() {
return "Portable Network Graphic (*.PNG)";
}
}
|
amidst
|
src\main\java\amidst\gui\main\SeedPrompt.java
|
package amidst.gui.main;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import amidst.documentation.NotThreadSafe;
import amidst.mojangapi.world.WorldSeed;
import amidst.mojangapi.world.WorldSeed.WorldSeedType;
import net.miginfocom.swing.MigLayout;
@NotThreadSafe
public class SeedPrompt {
private static final String TITLE = "Enter Seed";
private static final String STARTS_WITH_SPACE_TEXT = "WARNING: There is a space at the start!";
private static final String ENDS_WITH_SPACE_TEXT = "WARNING: There is a space at the end!";
private final JFrame frame;
private final JTextField textField;
private final JLabel seedLabel;
private final JLabel warningLabel;
private final JPanel panel;
private WorldSeed seed;
public SeedPrompt(JFrame frame) {
this.frame = frame;
this.textField = createTextField();
this.seedLabel = createSeedLabel();
this.warningLabel = createWarningLabel();
this.panel = createPanel();
}
private JTextField createTextField() {
JTextField result = new JTextField();
result.addAncestorListener(new AncestorListener() {
@Override
public void ancestorAdded(AncestorEvent e) {
grabFocus();
}
@Override
public void ancestorMoved(AncestorEvent e) {
grabFocus();
}
@Override
public void ancestorRemoved(AncestorEvent e) {
grabFocus();
}
});
result.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent e) {
update();
}
@Override
public void insertUpdate(DocumentEvent e) {
update();
}
@Override
public void removeUpdate(DocumentEvent e) {
update();
}
});
return result;
}
private JLabel createSeedLabel() {
JLabel result = new JLabel();
result.setFont(new Font("arial", Font.BOLD, 12));
return result;
}
private JLabel createWarningLabel() {
JLabel result = new JLabel();
result.setFont(new Font("arial", Font.BOLD, 12));
result.setForeground(Color.RED);
return result;
}
private JPanel createPanel() {
JPanel result = new JPanel(new MigLayout());
result.add(new JLabel("Enter your seed:"), "w 400!, wrap");
result.add(textField, "w 400!, wrap");
result.add(seedLabel, "w 400!, wrap");
result.add(warningLabel, "w 400!, h 30!");
return result;
}
private void grabFocus() {
// The call with invokeLater seems to help resolve an issue on Linux.
// Without it, the textField often does not get the focus.
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
textField.requestFocus();
}
});
}
private void update() {
seed = WorldSeed.fromUserInput(textField.getText());
if (WorldSeedType.TEXT == seed.getType() && seed.getText().startsWith(" ")) {
warningLabel.setText(STARTS_WITH_SPACE_TEXT);
} else if (WorldSeedType.TEXT == seed.getType() && seed.getText().endsWith(" ")) {
warningLabel.setText(ENDS_WITH_SPACE_TEXT);
} else {
warningLabel.setText("");
}
seedLabel.setText(seed.getLabel());
seedLabel.revalidate();
}
public WorldSeed askForSeed() {
update();
grabFocus();
if (JOptionPane.showConfirmDialog(frame, panel, TITLE, JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
return seed;
} else {
return null;
}
}
}
|
amidst
|
src\main\java\amidst\gui\main\UpdateInformationJson.java
|
package amidst.gui.main;
import amidst.AmidstVersion;
import amidst.documentation.GsonConstructor;
import amidst.documentation.Immutable;
@Immutable
public class UpdateInformationJson {
private volatile int major;
private volatile int minor;
private volatile int patch;
private volatile String message;
private volatile String downloadUrl;
@GsonConstructor
public UpdateInformationJson() {
}
public UpdateInformationJson(int major, int minor, int patch, String message, String downloadUrl) {
this.major = major;
this.minor = minor;
this.patch = patch;
this.downloadUrl = downloadUrl;
this.message = message;
}
public int getMajor() {
return major;
}
public int getMinor() {
return minor;
}
public int getPatch() {
return patch;
}
/**
* The message can be used to display additional information about the
* update.
*/
public String getMessage() {
return message;
}
public String getDownloadUrl() {
return downloadUrl;
}
public AmidstVersion createAmidstVersion() {
return new AmidstVersion(major, minor, patch);
}
}
|
amidst
|
src\main\java\amidst\gui\main\UpdateInformationRetriever.java
|
package amidst.gui.main;
import java.io.IOException;
import amidst.documentation.Immutable;
import amidst.documentation.NotNull;
import amidst.parsing.FormatException;
import amidst.parsing.json.JsonReader;
@Immutable
public enum UpdateInformationRetriever {
;
private static final String UPDATE_INFORMATION_JSON_URL = "https://toolbox4minecraft.github.io/amidst/api/update-information.json";
@NotNull
public static UpdateInformationJson retrieve() throws FormatException, IOException {
return JsonReader.readLocation(UPDATE_INFORMATION_JSON_URL, UpdateInformationJson.class);
}
}
|
amidst
|
src\main\java\amidst\gui\main\UpdatePrompt.java
|
package amidst.gui.main;
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.function.Consumer;
import java.util.function.Function;
import amidst.AmidstVersion;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotNull;
import amidst.documentation.NotThreadSafe;
import amidst.logging.AmidstLogger;
import amidst.logging.AmidstMessageBox;
import amidst.threading.WorkerExecutor;
@NotThreadSafe
public class UpdatePrompt {
@CalledOnlyBy(AmidstThread.EDT)
@NotNull
public static UpdatePrompt from(
AmidstVersion currentVersion,
WorkerExecutor workerExecutor,
MainWindowDialogs dialogs,
boolean silent) {
if (dialogs != null) {
if (silent) {
return new UpdatePrompt(
currentVersion,
workerExecutor,
NOOP_CONSUMER,
NOOP,
message -> dialogs.askToConfirmYesNo(TITLE, message));
} else {
return new UpdatePrompt(
currentVersion,
workerExecutor,
e -> dialogs.displayError(e),
() -> dialogs.displayInfo(TITLE, NO_UPDATES_AVAILABLE),
message -> dialogs.askToConfirmYesNo(TITLE, message));
}
} else {
if (silent) {
return new UpdatePrompt(
currentVersion,
workerExecutor,
NOOP_CONSUMER,
NOOP,
message -> AmidstMessageBox.askToConfirmYesNo(TITLE, message));
} else {
return new UpdatePrompt(
currentVersion,
workerExecutor,
e -> AmidstMessageBox.displayError(TITLE, e),
() -> AmidstMessageBox.displayInfo(TITLE, NO_UPDATES_AVAILABLE),
message -> AmidstMessageBox.askToConfirmYesNo(TITLE, message));
}
}
}
private static final String TITLE = "Amidst Updater";
private static final String NO_UPDATES_AVAILABLE = "There are no updates available.";
private static final Runnable NOOP = () -> {
};
private static final Consumer<Exception> NOOP_CONSUMER = e -> {
};
private final AmidstVersion currentVersion;
private final WorkerExecutor workerExecutor;
private final Consumer<Exception> exceptionConsumer;
private final Runnable noUpdatesDisplayer;
private final Function<String, Boolean> updateConfirmer;
@CalledOnlyBy(AmidstThread.EDT)
public UpdatePrompt(
AmidstVersion currentVersion,
WorkerExecutor workerExecutor,
Consumer<Exception> exceptionConsumer,
Runnable noUpdatesDisplayer,
Function<String, Boolean> updateConfirmer) {
this.currentVersion = currentVersion;
this.workerExecutor = workerExecutor;
this.exceptionConsumer = exceptionConsumer;
this.noUpdatesDisplayer = noUpdatesDisplayer;
this.updateConfirmer = updateConfirmer;
}
@CalledOnlyBy(AmidstThread.EDT)
public void check() {
workerExecutor.run(UpdateInformationRetriever::retrieve, this::displayResult, this::onCheckFailed);
}
@CalledOnlyBy(AmidstThread.EDT)
private void onCheckFailed(Exception e) {
AmidstLogger.warn(e, "unable to check for updates");
exceptionConsumer.accept(e);
}
@CalledOnlyBy(AmidstThread.EDT)
private void displayResult(UpdateInformationJson updateInformation) {
if (getUserChoice(updateInformation)) {
try {
openURL(new URI(updateInformation.getDownloadUrl()));
} catch (IOException | UnsupportedOperationException | URISyntaxException e) {
AmidstLogger.warn(e);
exceptionConsumer.accept(e);
}
}
}
@CalledOnlyBy(AmidstThread.EDT)
private boolean getUserChoice(UpdateInformationJson updateInformation) {
AmidstVersion newVersion = updateInformation.createAmidstVersion();
String message = updateInformation.getMessage();
if (newVersion.isNewerMajorVersionThan(currentVersion)) {
return askToConfirm(createMessage(message, newVersion, "major"));
} else if (newVersion.isNewerMinorVersionThan(currentVersion)) {
return askToConfirm(createMessage(message, newVersion, "minor"));
} else if (newVersion.isNewerPatchVersionThan(currentVersion)) {
return askToConfirm(createMessage(message, newVersion, "patch"));
} else if (newVersion.isSameVersionButOldPreReleaseAndNewStable(currentVersion)) {
return askToConfirm(createMessage(message, newVersion, "stable"));
} else {
AmidstLogger.info(NO_UPDATES_AVAILABLE);
noUpdatesDisplayer.run();
return false;
}
}
@CalledOnlyBy(AmidstThread.EDT)
private String createMessage(String message, AmidstVersion newVersion, String versionType) {
return "A new " + versionType + " version of Amidst is available:\n" + "Current Version: "
+ currentVersion.createVersionString() + "\n" + "New Version: " + newVersion.createVersionString()
+ "\n" + "Do you want to upgrade?" + createMessageSuffix(message);
}
@CalledOnlyBy(AmidstThread.EDT)
private String createMessageSuffix(String message) {
if (message != null && !message.isEmpty()) {
return "\n\n" + message;
} else {
return "";
}
}
@CalledOnlyBy(AmidstThread.EDT)
private boolean askToConfirm(String message) {
return updateConfirmer.apply(message);
}
@CalledOnlyBy(AmidstThread.EDT)
private void openURL(URI uri) throws IOException, UnsupportedOperationException {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.BROWSE)) {
desktop.browse(uri);
} else {
throw new UnsupportedOperationException("Unable to open browser page.");
}
} else {
throw new UnsupportedOperationException("Unable to open browser.");
}
}
}
|
amidst
|
src\main\java\amidst\gui\main\WorldSwitcher.java
|
package amidst.gui.main;
import amidst.AmidstSettings;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.fragment.FragmentManager;
import amidst.fragment.layer.LayerBuilder;
import amidst.gui.export.BiomeExporterDialog;
import amidst.gui.main.viewer.BiomeSelection;
import amidst.gui.main.viewer.ViewerFacade;
import amidst.gui.main.viewer.Zoom;
import amidst.logging.AmidstLogger;
import amidst.mojangapi.RunningLauncherProfile;
import amidst.mojangapi.file.MinecraftInstallation;
import amidst.mojangapi.minecraftinterface.MinecraftInterfaceException;
import amidst.mojangapi.world.World;
import amidst.mojangapi.world.WorldOptions;
import amidst.mojangapi.world.player.MovablePlayerList;
import amidst.mojangapi.world.player.WorldPlayerType;
import amidst.parsing.FormatException;
import amidst.threading.ThreadMaster;
import javax.swing.JFrame;
import java.awt.BorderLayout;
import java.awt.Container;
import java.io.IOException;
import java.nio.file.Path;
@NotThreadSafe
public class WorldSwitcher {
private final MinecraftInstallation minecraftInstallation;
private final RunningLauncherProfile runningLauncherProfile;
private final BiomeExporterDialog biomeExporterDialog;
private final AmidstSettings settings;
private final Zoom zoom;
private final LayerBuilder layerBuilder;
private final FragmentManager fragmentManager;
private final BiomeSelection biomeSelection;
private final ThreadMaster threadMaster;
private final JFrame frame;
private final Container contentPane;
private final MainWindowDialogs dialogs;
/**
* A reference to the main window.
*/
private final MainWindow mainWindow;
@CalledOnlyBy(AmidstThread.EDT)
public WorldSwitcher(
MinecraftInstallation minecraftInstallation,
RunningLauncherProfile runningLauncherProfile,
AmidstSettings settings,
Zoom zoom,
LayerBuilder layerBuilder,
FragmentManager fragmentManager,
BiomeSelection biomeSelection,
BiomeExporterDialog biomeExporterDialog,
ThreadMaster threadMaster,
JFrame frame,
Container contentPane,
MainWindow mainWindow,
MainWindowDialogs dialogs) {
this.minecraftInstallation = minecraftInstallation;
this.runningLauncherProfile = runningLauncherProfile;
this.settings = settings;
this.biomeExporterDialog = biomeExporterDialog;
this.zoom = zoom;
this.layerBuilder = layerBuilder;
this.fragmentManager = fragmentManager;
this.biomeSelection = biomeSelection;
this.threadMaster = threadMaster;
this.frame = frame;
this.contentPane = contentPane;
this.mainWindow = mainWindow;
this.dialogs = dialogs;
}
@CalledOnlyBy(AmidstThread.EDT)
public void displayWorld(WorldOptions worldOptions) {
try {
clearViewerFacade();
setWorld(runningLauncherProfile.createWorld(worldOptions));
} catch (IllegalStateException | MinecraftInterfaceException e) {
AmidstLogger.warn(e);
dialogs.displayError(e);
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void displayWorld(Path file) {
try {
clearViewerFacade();
setWorld(runningLauncherProfile.createWorldFromSaveGame(minecraftInstallation.newSaveGame(file)));
} catch (IllegalStateException | MinecraftInterfaceException | IOException | FormatException e) {
AmidstLogger.warn(e);
dialogs.displayError(e);
}
}
@CalledOnlyBy(AmidstThread.EDT)
private void clearViewerFacade() {
threadMaster.clearOnRepaintTick();
threadMaster.clearOnFragmentLoadTick();
ViewerFacade viewerFacade = mainWindow.getViewerFacade();
if (viewerFacade != null) {
mainWindow.setViewerFacade(null);
contentPane.remove(viewerFacade.getComponent());
viewerFacade.dispose();
}
mainWindow.getMenuBar().clear();
}
@CalledOnlyBy(AmidstThread.EDT)
private void setWorld(World world) {
if (decideWorldPlayerType(world.getMovablePlayerList())) {
ViewerFacade v = new ViewerFacade(
settings,
world,
fragmentManager,
zoom,
threadMaster.getWorkerExecutor(),
biomeExporterDialog,
layerBuilder,
biomeSelection,
mainWindow.getActions());
setViewerFacade(v);
} else {
frame.revalidate();
frame.repaint();
}
}
@CalledOnlyBy(AmidstThread.EDT)
private boolean decideWorldPlayerType(MovablePlayerList movablePlayerList) {
if (movablePlayerList.getWorldPlayerType().equals(WorldPlayerType.BOTH)) {
WorldPlayerType worldPlayerType = dialogs.askForWorldPlayerType();
if (worldPlayerType != null) {
movablePlayerList.setWorldPlayerType(worldPlayerType);
return true;
} else {
return false;
}
} else {
return true;
}
}
@CalledOnlyBy(AmidstThread.EDT)
private void setViewerFacade(ViewerFacade viewerFacade) {
contentPane.add(viewerFacade.getComponent(), BorderLayout.CENTER);
mainWindow.getMenuBar().set(viewerFacade);
frame.validate();
viewerFacade.loadPlayers();
threadMaster.setOnRepaintTick(viewerFacade.getOnRepainterTick());
threadMaster.setOnFragmentLoadTick(viewerFacade.getOnFragmentLoaderTick());
mainWindow.setViewerFacade(viewerFacade);
}
@CalledOnlyBy(AmidstThread.EDT)
public void clearWorld() {
clearViewerFacade();
}
}
|
amidst
|
src\main\java\amidst\gui\profileselect\LocalProfileComponent.java
|
package amidst.gui.profileselect;
import amidst.Application;
import amidst.ResourceLoader;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.logging.AmidstLogger;
import amidst.logging.AmidstMessageBox;
import amidst.mojangapi.LauncherProfileRunner;
import amidst.mojangapi.RunningLauncherProfile;
import amidst.mojangapi.file.LauncherProfile;
import amidst.mojangapi.file.UnresolvedLauncherProfile;
import amidst.mojangapi.file.Version;
import amidst.mojangapi.file.VersionListProvider;
import amidst.mojangapi.minecraftinterface.MinecraftInterfaceCreationException;
import amidst.parsing.FormatException;
import amidst.threading.WorkerExecutor;
import javax.imageio.ImageIO;
import java.awt.Image;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.List;
import java.util.Optional;
@NotThreadSafe
public class LocalProfileComponent extends ProfileComponent {
/**
* A reference to the Amidst instance.
*/
private final Application application;
private final WorkerExecutor workerExecutor;
private final List<Version> versions;
private final VersionListProvider versionListProvider;
private final LauncherProfileRunner launcherProfileRunner;
private final UnresolvedLauncherProfile unresolvedProfile;
private final Image scaledProfileIcon;
private volatile boolean isResolving = false;
private volatile boolean failedResolving = false;
private volatile boolean isLoading = false;
private volatile boolean failedLoading = false;
private volatile LauncherProfile resolvedProfile;
@CalledOnlyBy(AmidstThread.EDT)
public LocalProfileComponent(
Application application,
WorkerExecutor workerExecutor,
List<Version> versions,
VersionListProvider versionListProvider,
LauncherProfileRunner launcherProfileRunner,
UnresolvedLauncherProfile unresolvedProfile) {
this.application = application;
this.workerExecutor = workerExecutor;
this.versions = versions;
this.versionListProvider = versionListProvider;
this.launcherProfileRunner = launcherProfileRunner;
this.unresolvedProfile = unresolvedProfile;
this.scaledProfileIcon = createScaledProfileIcon();
initComponent();
}
@CalledOnlyBy(AmidstThread.EDT)
public Image createScaledProfileIcon() {
String icon = unresolvedProfile.getIcon();
if(icon != null && icon != "") {
final String prefix = "data:image/png;base64,";
Image image = null;
if(icon.startsWith(prefix)) {
icon = icon.substring(prefix.length());
try(ByteArrayInputStream stream = new ByteArrayInputStream(Base64.getDecoder().decode(icon))) {
image = ImageIO.read(stream);
} catch (IOException e) {
AmidstLogger.warn("Unable to decode base64 icon");
}
} else {
try {
image = ImageIO.read(ResourceLoader.getResourceURL("/amidst/icon/profileicons/" + icon + ".png"));
} catch (IOException | IllegalArgumentException e) {
AmidstLogger.error("Error reading icon: " + icon);
}
}
if(image != null) {
return image.getScaledInstance(32, 32, Image.SCALE_SMOOTH);
}
}
return null;
}
@CalledOnlyBy(AmidstThread.EDT)
@Override
public void resolveLater() {
resolvedProfile = null;
isResolving = true;
repaintComponent();
workerExecutor.run(this::tryResolve, this::resolveFinished);
}
@CalledOnlyBy(AmidstThread.WORKER)
private Optional<LauncherProfile> tryResolve() {
try {
List<Version> remote = versionListProvider.getRemote();
return Optional.of(unresolvedProfile.resolveToVanilla(remote == null ? versions : remote));
} catch (FormatException | IOException e) {
AmidstLogger.warn(e);
return Optional.empty();
}
}
@CalledOnlyBy(AmidstThread.EDT)
private void resolveFinished(Optional<LauncherProfile> launcherProfile) {
isResolving = false;
failedResolving = !launcherProfile.isPresent();
resolvedProfile = launcherProfile.orElse(null);
repaintComponent();
}
@Override
protected Image getScaledProfileIcon() {
return scaledProfileIcon;
}
@CalledOnlyBy(AmidstThread.EDT)
@Override
public void load() {
isLoading = true;
repaintComponent();
displayModdedMinecraftInfoIfNecessary();
workerExecutor.run(this::tryLoad, this::loadFinished);
}
@CalledOnlyBy(AmidstThread.EDT)
private void displayModdedMinecraftInfoIfNecessary() {
if (!resolvedProfile.isVersionListedInProfile()) {
String message = "Amidst does not support modded Minecraft versions! Using underlying vanilla Minecraft version "
+ resolvedProfile.getVersionId() + " instead.";
AmidstLogger.info(message);
AmidstMessageBox.displayInfo("Info", message);
}
}
@CalledOnlyBy(AmidstThread.WORKER)
private Optional<RunningLauncherProfile> tryLoad() {
try {
AmidstLogger.info(
"using minecraft launcher profile '" + resolvedProfile.getProfileName() + "' with versionId '"
+ resolvedProfile.getVersionName() + "'");
return Optional.of(launcherProfileRunner.run(resolvedProfile));
} catch (MinecraftInterfaceCreationException e) {
AmidstLogger.error(e);
AmidstMessageBox.displayError("Error", e);
return Optional.empty();
}
}
@CalledOnlyBy(AmidstThread.EDT)
private void loadFinished(Optional<RunningLauncherProfile> runningLauncherProfile) {
isLoading = false;
failedLoading = !runningLauncherProfile.isPresent();
repaintComponent();
if (runningLauncherProfile.isPresent()) {
application.displayMainWindow(runningLauncherProfile.get());
}
}
@CalledOnlyBy(AmidstThread.EDT)
@Override
protected boolean isResolving() {
return isResolving;
}
@CalledOnlyBy(AmidstThread.EDT)
@Override
protected boolean failedResolving() {
return failedResolving;
}
@CalledOnlyBy(AmidstThread.EDT)
@Override
protected boolean isLoading() {
return isLoading;
}
@CalledOnlyBy(AmidstThread.EDT)
@Override
protected boolean failedLoading() {
return failedLoading;
}
@CalledOnlyBy(AmidstThread.EDT)
@Override
protected boolean isReadyToLoad() {
return resolvedProfile != null;
}
@CalledOnlyBy(AmidstThread.EDT)
@Override
protected String getProfileName() {
return unresolvedProfile.getName();
}
@CalledOnlyBy(AmidstThread.EDT)
@Override
protected String getVersionName() {
if (resolvedProfile != null) {
return resolvedProfile.getVersionName();
} else {
return "";
}
}
}
|
amidst
|
src\main\java\amidst\gui\profileselect\ProfileComponent.java
|
package amidst.gui.profileselect;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
import amidst.ResourceLoader;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
@NotThreadSafe
public abstract class ProfileComponent implements Comparable<ProfileComponent>{
@SuppressWarnings("serial")
private class Component extends JComponent {
private final FontMetrics statusFontMetrics = getFontMetrics(STATUS_FONT);
private final FontMetrics versionFontMetrics = getFontMetrics(VERSION_NAME_FONT);
private final FontMetrics profileFontMetrics = getFontMetrics(PROFILE_NAME_FONT);
private int versionNameX;
private int oldWidth;
private String oldVersionName;
private String oldProfileName;
@CalledOnlyBy(AmidstThread.EDT)
public Component() {
this.setMinimumSize(new Dimension(300, 40));
this.setPreferredSize(new Dimension(PREFERRED_WIDTH, PREFERRED_HEIGHT));
}
@CalledOnlyBy(AmidstThread.EDT)
@Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
drawBackground(g2d);
updateIfNecessary();
drawProfileIcon(g2d);
drawVersionName(g2d);
drawProfileName(g2d);
drawStatus(g2d);
drawStatusIcon(g2d);
}
@CalledOnlyBy(AmidstThread.EDT)
private void drawBackground(Graphics2D g2d) {
g2d.setColor(getBackgroundColor());
g2d.fillRect(0, 0, getWidth(), getHeight());
}
@CalledOnlyBy(AmidstThread.EDT)
private void updateIfNecessary() {
int width = getWidth();
String versionName = getVersionName();
String profileName = getProfileName();
if (oldVersionName == null || oldWidth != width || !oldVersionName.equals(versionName)) {
versionNameX = width - 40 - versionFontMetrics.stringWidth(versionName);
oldWidth = width;
oldVersionName = versionName;
oldProfileName = createProfileName(profileName, versionNameX - 25, 40);
}
}
@CalledOnlyBy(AmidstThread.EDT)
private String createProfileName(String profileName, int maxWidth, int xOffset) {
String result = profileName;
if (profileFontMetrics.stringWidth(result) + xOffset > maxWidth) {
int widthSum = 0;
for (int i = 0; i < result.length(); i++) {
widthSum += profileFontMetrics.charWidth(result.charAt(i));
if (widthSum + xOffset > maxWidth) {
return result.substring(0, i) + "...";
}
}
}
return result;
}
@CalledOnlyBy(AmidstThread.EDT)
private void drawProfileIcon(Graphics2D g2d) {
Image icon = getScaledProfileIcon();
if(icon != null) {
g2d.drawImage(icon, 4, 4, null);
}
}
@CalledOnlyBy(AmidstThread.EDT)
private void drawVersionName(Graphics2D g2d) {
g2d.setColor(Color.black);
g2d.setFont(VERSION_NAME_FONT);
g2d.drawString(oldVersionName, versionNameX, 20);
}
@CalledOnlyBy(AmidstThread.EDT)
private void drawProfileName(Graphics2D g2d) {
g2d.setColor(Color.black);
g2d.setFont(PROFILE_NAME_FONT);
g2d.drawString(oldProfileName, 40, 30);
}
@CalledOnlyBy(AmidstThread.EDT)
private void drawStatus(Graphics2D g2d) {
g2d.setColor(Color.gray);
g2d.setFont(STATUS_FONT);
String loadingStatus = getLoadingStatus();
int stringWidth = statusFontMetrics.stringWidth(loadingStatus);
g2d.drawString(loadingStatus, getWidth() - 40 - stringWidth, 32);
}
@CalledOnlyBy(AmidstThread.EDT)
private void drawStatusIcon(Graphics2D g2d) {
Image icon = getStatusIcon();
g2d.drawImage(icon, getWidth() - icon.getWidth(null) - 5, 4, null);
}
}
private static final Font STATUS_FONT = new Font("arial", Font.BOLD, 10);
private static final Font VERSION_NAME_FONT = new Font("arial", Font.BOLD, 16);
private static final Font PROFILE_NAME_FONT = new Font("arial", Font.BOLD, 30);
private static final BufferedImage ACTIVE_ICON = ResourceLoader.getImage("/amidst/gui/profileselect/active.png");
private static final BufferedImage INACTIVE_ICON = ResourceLoader
.getImage("/amidst/gui/profileselect/inactive.png");
private static final BufferedImage LOADING_ICON = ResourceLoader.getImage("/amidst/gui/profileselect/loading.png");
private static final Color SELECTED_BG_COLOR = new Color(160, 190, 255);
private static final Color LOADING_BG_COLOR = new Color(112, 203, 91);
private static final Color DEFAULT_BG_COLOR = Color.white;
private static final Color FAILED_BG_COLOR = new Color(250, 160, 160);
private static final Color SELECTED_FAILED_BG_COLOR = new Color(205, 175, 208);
public static final int PREFERRED_WIDTH = 500;
public static final int PREFERRED_HEIGHT = 40;
private Component component;
private boolean isSelected = false;
/**
* This cannot be put in the constructor, because that would cause a call to
* e.g. getProfileName by the drawing function before the derived class is
* constructed.
*/
@CalledOnlyBy(AmidstThread.EDT)
protected void initComponent() {
this.component = new Component();
}
@CalledOnlyBy(AmidstThread.EDT)
public boolean isSelected() {
return isSelected;
}
@CalledOnlyBy(AmidstThread.EDT)
public void setSelected(boolean isSelected) {
if (this.isSelected != isSelected) {
this.isSelected = isSelected;
component.repaint();
}
}
@CalledOnlyBy(AmidstThread.EDT)
public Component getComponent() {
return component;
}
@CalledOnlyBy(AmidstThread.EDT)
protected void repaintComponent() {
component.repaint();
}
@CalledOnlyBy(AmidstThread.EDT)
private String getLoadingStatus() {
if (failedLoading()) {
return "failed loading";
} else if (isLoading()) {
return "loading";
} else if (failedResolving()) {
return "not found";
} else if (isResolving()) {
return "resolving";
} else {
return "found";
}
}
@CalledOnlyBy(AmidstThread.EDT)
private Image getStatusIcon() {
if (failedLoading()) {
return INACTIVE_ICON;
} else if (isLoading()) {
return LOADING_ICON;
} else if (failedResolving()) {
return INACTIVE_ICON;
} else if (isResolving()) {
return INACTIVE_ICON;
} else {
return ACTIVE_ICON;
}
}
@CalledOnlyBy(AmidstThread.EDT)
protected Image getScaledProfileIcon() {
return null;
}
@CalledOnlyBy(AmidstThread.EDT)
private Color getBackgroundColor() {
if (failedLoading()) {
if(isSelected) {
return SELECTED_FAILED_BG_COLOR;
} else {
return FAILED_BG_COLOR;
}
} else if (isLoading()) {
return LOADING_BG_COLOR;
} else if (failedResolving()) {
if(isSelected) {
return SELECTED_FAILED_BG_COLOR;
} else {
return FAILED_BG_COLOR;
}
} else if (isSelected) {
return SELECTED_BG_COLOR;
} else {
return DEFAULT_BG_COLOR;
}
}
@CalledOnlyBy(AmidstThread.EDT)
protected abstract void load();
@CalledOnlyBy(AmidstThread.EDT)
protected abstract boolean isResolving();
@CalledOnlyBy(AmidstThread.EDT)
protected abstract boolean failedResolving();
@CalledOnlyBy(AmidstThread.EDT)
protected abstract boolean isLoading();
@CalledOnlyBy(AmidstThread.EDT)
protected abstract boolean failedLoading();
@CalledOnlyBy(AmidstThread.EDT)
protected abstract boolean isReadyToLoad();
@CalledOnlyBy(AmidstThread.EDT)
protected abstract String getProfileName();
@CalledOnlyBy(AmidstThread.EDT)
protected abstract String getVersionName();
@CalledOnlyBy(AmidstThread.EDT)
public abstract void resolveLater();
@Override
public int compareTo(ProfileComponent o) {
return this.getProfileName().compareToIgnoreCase(o.getProfileName());
}
}
|
amidst
|
src\main\java\amidst\gui\profileselect\ProfileSelectPanel.java
|
package amidst.gui.profileselect;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.settings.Setting;
import net.miginfocom.swing.MigLayout;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* The JPanel that lists the individual profiles installed.
*/
@NotThreadSafe
public class ProfileSelectPanel {
@NotThreadSafe
@SuppressWarnings("serial")
private class Component extends JPanel {
private static final int INVALID_EMPTY_MESSAGE_WIDTH = -1;
private int emptyMessageWidth = INVALID_EMPTY_MESSAGE_WIDTH;
private final String oldEmptyMessage;
@CalledOnlyBy(AmidstThread.EDT)
public Component() {
this.oldEmptyMessage = emptyMessage;
}
@CalledOnlyBy(AmidstThread.EDT)
@Override
public void paintChildren(Graphics g) {
super.paintChildren(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.gray);
for (int i = 1; i <= profileComponents.size(); i++) {
g2d.drawLine(0, i * 40, getWidth(), i * 40);
}
}
@CalledOnlyBy(AmidstThread.EDT)
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (g instanceof Graphics2D g2d) {
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2d.setColor(Color.white);
g2d.fillRect(0, 0, getWidth(), getHeight());
if (profileComponents.isEmpty()) {
g2d.setColor(Color.gray);
g2d.setFont(new Font("arial", Font.BOLD, 30));
if (!oldEmptyMessage.equals(emptyMessage) || emptyMessageWidth == INVALID_EMPTY_MESSAGE_WIDTH) {
emptyMessageWidth = g2d.getFontMetrics().stringWidth(emptyMessage);
}
int x = (getWidth() >> 1) - (emptyMessageWidth >> 1);
g2d.drawString(emptyMessage, x, 30);
}
}
}
}
private static final int INVALID_INDEX = -1;
private final Setting<String> lastProfileSetting;
private final Component component;
private final List<ProfileComponent> profileComponents = new ArrayList<>();
private ProfileComponent selected = null;
private String emptyMessage = "Scanning...";
@CalledOnlyBy(AmidstThread.EDT)
public ProfileSelectPanel(Setting<String> lastProfileSetting) {
this.lastProfileSetting = lastProfileSetting;
component = new Component();
component.setLayout(new MigLayout("ins 0", "", "[]0[]"));
component.addMouseListener(createMouseListener());
}
@CalledOnlyBy(AmidstThread.EDT)
private MouseListener createMouseListener() {
return new MouseAdapter() {
@CalledOnlyBy(AmidstThread.EDT)
@Override
public void mousePressed(MouseEvent e) {
if (!isLoading()) {
Point mousePosition = e.getPoint();
select(getSelectedIndexFromYCoordinate(mousePosition));
if (isLoadButtonClicked(mousePosition)) {
loadSelectedProfile();
}
}
}
};
}
@CalledOnlyBy(AmidstThread.EDT)
public KeyListener createKeyListener() {
return new KeyAdapter() {
@CalledOnlyBy(AmidstThread.EDT)
@Override
public void keyPressed(KeyEvent e) {
if (!isLoading()) {
switch (e.getKeyCode()) {
case KeyEvent.VK_DOWN -> select(profileComponents.indexOf(selected) + 1);
case KeyEvent.VK_UP -> select(profileComponents.indexOf(selected) - 1);
case KeyEvent.VK_ENTER -> loadSelectedProfile();
}
}
}
};
}
@CalledOnlyBy(AmidstThread.EDT)
private int getSelectedIndexFromYCoordinate(Point mousePosition) {
return mousePosition.y / 40;
}
@CalledOnlyBy(AmidstThread.EDT)
private boolean isLoadButtonClicked(Point mousePosition) {
return mousePosition.x > component.getWidth() - 40;
}
@CalledOnlyBy(AmidstThread.EDT)
public void selectFirst() {
select(0);
}
@CalledOnlyBy(AmidstThread.EDT)
public void select(String profileName) {
select(getIndex(profileName));
}
@CalledOnlyBy(AmidstThread.EDT)
private int getIndex(String profileName) {
for (int i = 0; i < profileComponents.size(); i++) {
if (profileComponents.get(i).getProfileName().equals(profileName)) {
return i;
}
}
return INVALID_INDEX;
}
@CalledOnlyBy(AmidstThread.EDT)
private void select(int index) {
if (selected != null) {
selected.setSelected(false);
selected = null;
}
int i;
if (profileComponents.isEmpty()) {
i = INVALID_INDEX;
} else if (index < 0) {
i = 0;
} else if (index >= profileComponents.size()) {
i = profileComponents.size() - 1;
} else {
i = index;
}
if (i != INVALID_INDEX) {
selected = profileComponents.get(i);
selected.setSelected(true);
}
}
@CalledOnlyBy(AmidstThread.EDT)
private void loadSelectedProfile() {
if (selected != null && selected.isReadyToLoad()) {
lastProfileSetting.set(selected.getProfileName());
selected.load();
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void addProfile(ProfileComponent profile) {
profileComponents.add(profile);
// Sort and re-add all components
profileComponents.sort(Comparator.nullsFirst(Comparator.naturalOrder()));
component.removeAll();
for (ProfileComponent p: profileComponents) {
component.add(p.getComponent(), "growx, pushx, wrap");
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void setEmptyMessage(String emptyMessage) {
this.emptyMessage = emptyMessage;
component.repaint();
}
@CalledOnlyBy(AmidstThread.EDT)
public JPanel getComponent() {
return component;
}
@CalledOnlyBy(AmidstThread.EDT)
private boolean isLoading() {
for (ProfileComponent profileComponent : profileComponents) {
if (profileComponent.isLoading()) {
return true;
}
}
return false;
}
@CalledOnlyBy(AmidstThread.EDT)
public void resolveAllLater() {
if (!isLoading()) {
profileComponents.forEach(ProfileComponent::resolveLater);
}
}
}
|
amidst
|
src\main\java\amidst\gui\profileselect\ProfileSelectWindow.java
|
package amidst.gui.profileselect;
import amidst.AmidstSettings;
import amidst.Application;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.logging.AmidstLogger;
import amidst.logging.AmidstMessageBox;
import amidst.mojangapi.LauncherProfileRunner;
import amidst.mojangapi.file.MinecraftInstallation;
import amidst.mojangapi.file.UnresolvedLauncherProfile;
import amidst.mojangapi.file.Version;
import amidst.mojangapi.file.VersionListProvider;
import amidst.threading.WorkerExecutor;
import amidst.util.SwingUtils;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import java.awt.Font;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import static amidst.Amidst.BUFFERED_IMAGES;
/**
* A window that shows the profiles that are installed.
* <p>
* Some profiles may be modded or higher than the supported
* Amidst application.
*/
@NotThreadSafe
public class ProfileSelectWindow {
private static final int HEIGHT_IN_PROFILE_COMPONENTS = 13;
/**
* The window that contains the profile selection list.
*/
private final JFrame frame;
private volatile boolean isDisposed = false;
@CalledOnlyBy(AmidstThread.EDT)
public ProfileSelectWindow(
Application application,
WorkerExecutor workerExecutor,
List<Version> versions,
VersionListProvider versionListProvider,
MinecraftInstallation minecraftInstallation,
LauncherProfileRunner launcherProfileRunner,
AmidstSettings settings) {
frame = new JFrame("Profile Selector");
frame.setIconImages(BUFFERED_IMAGES);
frame.getContentPane().setLayout(new MigLayout());
JLabel title = new JLabel("Please select a Minecraft profile:", SwingConstants.CENTER);
title.setFont(new Font("arial", Font.BOLD, 16));
frame.add(title, "h 20!,w :400:, growx, pushx, wrap");
ProfileSelectPanel profileSelectPanel = new ProfileSelectPanel(settings.lastProfile);
JScrollPane scrollPane = new JScrollPane(profileSelectPanel.getComponent());
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.getVerticalScrollBar().setUnitIncrement(14);
// The preferred width should be at least a scrollbar-width wider than the
// ProfileComponent's preferredSize width of 500 (so 520?). The preferred
// height should allow the dialog to fit easily on a 720p display, while
// being nicely divisible by ProfileComponent's height of 40 (so 520 again
// then?).
int scrollBarWidth = (Integer) UIManager.get("ScrollBar.width");
int preferredWidth = ProfileComponent.PREFERRED_WIDTH + scrollBarWidth;
int preferredHeight = ProfileComponent.PREFERRED_HEIGHT * HEIGHT_IN_PROFILE_COMPONENTS;
frame.add(scrollPane, "grow, push, w :" + preferredWidth + ":, h 80:" + preferredHeight + ":");
frame.pack();
frame.addKeyListener(profileSelectPanel.createKeyListener());
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
application.exitGracefully();
}
});
frame.setLocationRelativeTo(null);
frame.setVisible(true);
workerExecutor.run(() -> {
AmidstLogger.info("Scanning for profiles.");
List<UnresolvedLauncherProfile> launcherProfiles = minecraftInstallation.readLauncherProfiles();
AmidstLogger.info("Successfully loaded profile list.");
return launcherProfiles;
}, launcherProfiles -> {
if (launcherProfiles.isEmpty()) {
AmidstLogger.warn("No profiles found in launcher_profiles.json");
profileSelectPanel.setEmptyMessage("No profiles found");
} else {
launcherProfiles.stream()
.map(p ->
new LocalProfileComponent(
application,
workerExecutor,
versions,
versionListProvider,
launcherProfileRunner,
p
)
).forEach(profileSelectPanel::addProfile);
versionListProvider.onDownloadRemoteFinished(() -> {
if (!isDisposed) {
profileSelectPanel.resolveAllLater();
}
});
profileSelectPanel.resolveAllLater();
}
String profileName = settings.lastProfile.get();
if (profileName != null && !profileName.isEmpty()) {
profileSelectPanel.select(profileName);
} else {
profileSelectPanel.selectFirst();
}
frame.pack();
}, e -> {
AmidstLogger.error(e, "Error reading launcher_profiles.json");
AmidstMessageBox.displayError("Error", e, "Error reading launcher_profiles.json");
profileSelectPanel.setEmptyMessage("Failed loading");
});
}
@CalledOnlyBy(AmidstThread.EDT)
public void dispose() {
isDisposed = true;
SwingUtils.destroyComponentTree(frame);
}
}
|
amidst
|
src\main\java\amidst\gui\seedsearcher\SeedSearcher.java
|
package amidst.gui.seedsearcher;
import java.util.function.Consumer;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.gui.main.MainWindowDialogs;
import amidst.logging.AmidstLogger;
import amidst.mojangapi.RunningLauncherProfile;
import amidst.mojangapi.minecraftinterface.MinecraftInterfaceException;
import amidst.mojangapi.world.World;
import amidst.mojangapi.world.WorldOptions;
import amidst.mojangapi.world.WorldSeed;
import amidst.threading.WorkerExecutor;
import amidst.threading.worker.ProgressReporter;
import amidst.threading.worker.ProgressReportingWorker;
@NotThreadSafe
public class SeedSearcher {
private final MainWindowDialogs dialogs;
private final RunningLauncherProfile runningLauncherProfile;
private final WorkerExecutor workerExecutor;
private volatile boolean isSearching = false;
private volatile boolean isStopRequested = false;
@CalledOnlyBy(AmidstThread.EDT)
public SeedSearcher(
MainWindowDialogs dialogs,
RunningLauncherProfile runningLauncherProfile,
WorkerExecutor workerExecutor) {
this.dialogs = dialogs;
this.runningLauncherProfile = runningLauncherProfile;
this.workerExecutor = workerExecutor;
}
@CalledOnlyBy(AmidstThread.EDT)
public void search(SeedSearcherConfiguration configuration, Consumer<WorldOptions> onWorldFound) {
this.isSearching = true;
this.isStopRequested = false;
workerExecutor.run(createSearcher(configuration), onWorldFound);
}
@CalledOnlyBy(AmidstThread.EDT)
private ProgressReportingWorker<WorldOptions> createSearcher(SeedSearcherConfiguration configuration) {
return reporter -> this.trySearch(reporter, configuration);
}
@CalledOnlyBy(AmidstThread.EDT)
public void stop() {
this.isStopRequested = true;
}
@CalledOnlyBy(AmidstThread.EDT)
public void dispose() {
stop();
}
@CalledOnlyBy(AmidstThread.EDT)
public boolean isSearching() {
return isSearching;
}
@CalledOnlyBy(AmidstThread.EDT)
public boolean isStopRequested() {
return isStopRequested;
}
@CalledOnlyBy(AmidstThread.WORKER)
private void trySearch(ProgressReporter<WorldOptions> reporter, SeedSearcherConfiguration configuration) {
try {
doSearch(reporter, configuration);
} catch (IllegalStateException | MinecraftInterfaceException e) {
AmidstLogger.warn(e);
dialogs.displayError(e);
} finally {
this.isSearching = false;
this.isStopRequested = false;
}
}
@CalledOnlyBy(AmidstThread.WORKER)
private void doSearch(ProgressReporter<WorldOptions> reporter, SeedSearcherConfiguration configuration)
throws IllegalStateException,
MinecraftInterfaceException {
do {
doSearchOne(reporter, configuration);
} while (configuration.isSearchContinuously() && !isStopRequested);
}
@CalledOnlyBy(AmidstThread.WORKER)
private void doSearchOne(ProgressReporter<WorldOptions> reporter, SeedSearcherConfiguration configuration)
throws IllegalStateException,
MinecraftInterfaceException {
while (!isStopRequested) {
WorldOptions worldOptions = new WorldOptions(WorldSeed.random(), configuration.getWorldType());
World world = runningLauncherProfile.createWorld(worldOptions);
if (configuration.getWorldFilter().isValid(world)) {
reporter.report(worldOptions);
break;
}
}
}
}
|
amidst
|
src\main\java\amidst\gui\seedsearcher\SeedSearcherConfiguration.java
|
package amidst.gui.seedsearcher;
import amidst.documentation.Immutable;
import amidst.mojangapi.world.WorldType;
import amidst.mojangapi.world.filter.WorldFilter;
@Immutable
public class SeedSearcherConfiguration {
private final WorldFilter worldFilter;
private final WorldType worldType;
private final boolean searchContinuously;
public SeedSearcherConfiguration(WorldFilter worldFilter, WorldType worldType, boolean searchContinuously) {
this.worldFilter = worldFilter;
this.worldType = worldType;
this.searchContinuously = searchContinuously;
}
public WorldFilter getWorldFilter() {
return worldFilter;
}
public WorldType getWorldType() {
return worldType;
}
public boolean isSearchContinuously() {
return searchContinuously;
}
}
|
amidst
|
src\main\java\amidst\gui\seedsearcher\SeedSearcherWindow.java
|
package amidst.gui.seedsearcher;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.gui.main.MainWindowDialogs;
import amidst.gui.main.WorldSwitcher;
import amidst.logging.AmidstLogger;
import amidst.mojangapi.file.json.filter.WorldFilterJson_MatchAll;
import amidst.mojangapi.world.WorldOptions;
import amidst.mojangapi.world.WorldType;
import amidst.mojangapi.world.filter.WorldFilter;
import amidst.util.SwingUtils;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.util.Optional;
import static amidst.Amidst.BUFFERED_IMAGES;
@NotThreadSafe
public class SeedSearcherWindow {
private final MainWindowDialogs dialogs;
private final WorldSwitcher worldSwitcher;
private final SeedSearcher seedSearcher;
private final JTextArea searchQueryTextArea;
private final JComboBox<WorldType> worldTypeComboBox;
private final JCheckBox searchContinuouslyCheckBox;
private final JButton searchButton;
private final JFrame frame;
@CalledOnlyBy(AmidstThread.EDT)
public SeedSearcherWindow(
MainWindowDialogs dialogs,
WorldSwitcher worldSwitcher,
SeedSearcher seedSearcher) {
this.dialogs = dialogs;
this.worldSwitcher = worldSwitcher;
this.seedSearcher = seedSearcher;
this.searchQueryTextArea = createSearchQueryTextArea();
this.worldTypeComboBox = createWorldTypeComboBox();
this.searchContinuouslyCheckBox = createSearchContinuouslyCheckBox();
this.searchButton = createSearchButton();
this.frame = createFrame();
}
@CalledOnlyBy(AmidstThread.EDT)
public void show() {
this.frame.setVisible(true);
updateGUI();
}
@CalledOnlyBy(AmidstThread.EDT)
private JTextArea createSearchQueryTextArea() {
return new JTextArea();
}
@CalledOnlyBy(AmidstThread.EDT)
private JComboBox<WorldType> createWorldTypeComboBox() {
return new JComboBox<>(WorldType.getSelectableArray());
}
@CalledOnlyBy(AmidstThread.EDT)
private JCheckBox createSearchContinuouslyCheckBox() {
return new JCheckBox("search continuously");
}
@CalledOnlyBy(AmidstThread.EDT)
private JButton createSearchButton() {
JButton result = new JButton("Search");
result.addActionListener(e -> searchButtonClicked());
return result;
}
@CalledOnlyBy(AmidstThread.EDT)
private JFrame createFrame() {
JFrame result = new JFrame("Seed Searcher");
result.setIconImages(BUFFERED_IMAGES);
result.getContentPane().setLayout(new MigLayout());
result.add(new JLabel("Search Query:"), "growx, pushx, wrap");
result.add(createScrollPane(searchQueryTextArea), "grow, push, wrap");
result.add(new JLabel("World Type:"), "growx, pushx, wrap");
result.add(worldTypeComboBox, "growx, pushx, wrap");
result.add(searchContinuouslyCheckBox, "growx, pushx, wrap");
result.add(searchButton, "pushx, wrap");
result.setSize(800, 600);
result.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
return result;
}
@CalledOnlyBy(AmidstThread.EDT)
private JScrollPane createScrollPane(JTextArea textArea) {
JScrollPane result = new JScrollPane(textArea);
result.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
result.setBorder(new LineBorder(Color.darkGray, 1));
return result;
}
@CalledOnlyBy(AmidstThread.EDT)
private void searchButtonClicked() {
if (seedSearcher.isSearching()) {
seedSearcher.stop();
} else {
Optional<SeedSearcherConfiguration> configuration = createSeedSearcherConfiguration();
if (configuration.isPresent()) {
SeedSearcherConfiguration seedSearcherConfiguration = configuration.get();
seedSearcher.search(seedSearcherConfiguration, worldOptions -> seedFound(worldOptions));
} else {
AmidstLogger.warn("invalid configuration");
dialogs.displayError("invalid configuration");
}
}
updateGUI();
}
@CalledOnlyBy(AmidstThread.EDT)
private Optional<SeedSearcherConfiguration> createSeedSearcherConfiguration() {
return WorldFilterJson_MatchAll
.from(searchQueryTextArea.getText())
.flatMap(WorldFilterJson_MatchAll::createValidWorldFilter)
.map(this::createSeedSearcherConfiguration);
}
@CalledOnlyBy(AmidstThread.EDT)
private SeedSearcherConfiguration createSeedSearcherConfiguration(WorldFilter worldFilter) {
return new SeedSearcherConfiguration(
worldFilter,
(WorldType) worldTypeComboBox.getSelectedItem(),
searchContinuouslyCheckBox.isSelected());
}
@CalledOnlyBy(AmidstThread.EDT)
private void seedFound(WorldOptions worldOptions) {
worldSwitcher.displayWorld(worldOptions);
updateGUI();
}
@CalledOnlyBy(AmidstThread.EDT)
private void updateGUI() {
if (seedSearcher.isSearching() && !seedSearcher.isStopRequested()) {
searchButton.setText("Stop");
searchQueryTextArea.setEditable(false);
worldTypeComboBox.setEnabled(false);
searchContinuouslyCheckBox.setEnabled(false);
} else {
searchButton.setText("Search");
searchQueryTextArea.setEditable(true);
worldTypeComboBox.setEnabled(true);
searchContinuouslyCheckBox.setEnabled(true);
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void dispose() {
seedSearcher.dispose();
SwingUtils.destroyComponentTree(frame);
}
}
|
amidst
|
src\main\java\amidst\gui\main\menu\AmidstMenu.java
|
package amidst.gui.main.menu;
import java.util.function.Consumer;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.MenuElement;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.gui.main.viewer.ViewerFacade;
@NotThreadSafe
public class AmidstMenu {
private final JMenuBar menuBar;
private final JMenu worldMenu;
private final JMenuItem savePlayerLocationsMenu;
private final JMenuItem reloadPlayerLocationsMenu;
private final LayersMenu layersMenu;
@CalledOnlyBy(AmidstThread.EDT)
public AmidstMenu(
JMenuBar menuBar,
JMenu worldMenu,
JMenuItem savePlayerLocationsMenu,
JMenuItem reloadPlayerLocationsMenu,
LayersMenu layersMenu) {
this.menuBar = menuBar;
this.worldMenu = worldMenu;
this.savePlayerLocationsMenu = savePlayerLocationsMenu;
this.reloadPlayerLocationsMenu = reloadPlayerLocationsMenu;
this.layersMenu = layersMenu;
}
@CalledOnlyBy(AmidstThread.EDT)
public JMenuBar getMenuBar() {
return menuBar;
}
@CalledOnlyBy(AmidstThread.EDT)
public void setMenuItemsEnabled(String[] textRepresentations, boolean enabled) {
runOnMenuItems(menuBar, textRepresentations, i -> i.setEnabled(enabled));
}
@CalledOnlyBy(AmidstThread.EDT)
private void runOnMenuItems(MenuElement menuElement, String[] textRepresentations, Consumer<JMenuItem> consumer) {
boolean doOnAll = (textRepresentations == null);
MenuElement[] elements = menuElement.getSubElements();
if(elements != null) {
for(MenuElement element : elements) {
if(element instanceof JMenuItem) {
if(!doOnAll) {
for(String s : textRepresentations) {
if(((JMenuItem) element).getText().equals(s)) {
consumer.accept((JMenuItem) element);
}
}
} else {
consumer.accept((JMenuItem) element);
}
}
runOnMenuItems(element, textRepresentations, consumer);
}
}
}
@CalledOnlyBy(AmidstThread.EDT)
public void set(ViewerFacade viewerFacade) {
worldMenu.setEnabled(true);
savePlayerLocationsMenu.setEnabled(viewerFacade.canSavePlayerLocations());
reloadPlayerLocationsMenu.setEnabled(viewerFacade.canLoadPlayerLocations());
layersMenu.init(viewerFacade);
}
@CalledOnlyBy(AmidstThread.EDT)
public void clear() {
worldMenu.setEnabled(false);
savePlayerLocationsMenu.setEnabled(false);
reloadPlayerLocationsMenu.setEnabled(false);
layersMenu.disable();
}
}
|
amidst
|
src\main\java\amidst\gui\main\menu\AmidstMenuBuilder.java
|
package amidst.gui.main.menu;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import javax.swing.AbstractButton;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JSlider;
import javax.swing.MenuSelectionManager;
import javax.swing.UIManager;
import amidst.AmidstSettings;
import amidst.FeatureToggles;
import amidst.documentation.NotThreadSafe;
import amidst.gui.main.Actions;
import amidst.gui.main.AmidstLookAndFeel;
import amidst.mojangapi.world.WorldType;
import amidst.settings.Setting;
import amidst.settings.biomeprofile.BiomeProfileDirectory;
@NotThreadSafe
public class AmidstMenuBuilder {
private final AmidstSettings settings;
private final Actions actions;
private final BiomeProfileDirectory biomeProfileDirectory;
private final JMenuBar menuBar;
private JMenu worldMenu;
private JMenuItem savePlayerLocationsMenu;
private JMenuItem reloadPlayerLocationsMenu;
private LayersMenu layersMenu;
public AmidstMenuBuilder(AmidstSettings settings, Actions actions, BiomeProfileDirectory biomeProfileDirectory) {
this.settings = settings;
this.actions = actions;
this.biomeProfileDirectory = biomeProfileDirectory;
this.menuBar = createMenuBar();
}
public AmidstMenu construct() {
return new AmidstMenu(
menuBar,
worldMenu,
savePlayerLocationsMenu,
reloadPlayerLocationsMenu,
layersMenu);
}
private JMenuBar createMenuBar() {
JMenuBar result = new JMenuBar();
result.add(create_File());
worldMenu = result.add(create_World());
result.add(create_Layers());
result.add(create_Settings());
result.add(create_Help());
return result;
}
private JMenu create_File() {
JMenu result = new JMenu("File");
result.setMnemonic(KeyEvent.VK_F);
// @formatter:off
Menus.item(result, actions::newFromSeed, "New From Seed ...", KeyEvent.VK_N, MenuShortcuts.NEW_FROM_SEED);
Menus.item(result, actions::newFromRandom, "New From Random Seed", KeyEvent.VK_R, MenuShortcuts.NEW_FROM_RANDOM_SEED);
if (FeatureToggles.SEED_SEARCH) {
Menus.item(result, actions::searchForRandom, "Search for Random Seed", KeyEvent.VK_F, MenuShortcuts.SEARCH_FOR_RANDOM_SEED);
}
Menus.item(result, actions::openSaveGame, "Open Save Game ...", KeyEvent.VK_O, MenuShortcuts.OPEN_SAVE_GAME);
result.addSeparator();
Menus.item(result, actions::switchProfile, "Switch Profile ...", KeyEvent.VK_P, MenuShortcuts.SWITCH_PROFILE);
Menus.item(result, actions::exit, "Exit", KeyEvent.VK_X, MenuShortcuts.EXIT);
// @formatter:on
return result;
}
private JMenu create_World() {
JMenu result = new JMenu("World");
result.setEnabled(false);
result.setMnemonic(KeyEvent.VK_W);
// @formatter:off
Menus.item(result, actions::goToCoordinate, "Go to Coordinate ...", KeyEvent.VK_C, MenuShortcuts.GO_TO_COORDINATE);
Menus.item(result, actions::goToSpawn, "Go to World Spawn", KeyEvent.VK_S, MenuShortcuts.GO_TO_WORLD_SPAWN);
Menus.item(result, actions::goToStronghold, "Go to Stronghold ...", KeyEvent.VK_H, MenuShortcuts.GO_TO_STRONGHOLD);
Menus.item(result, actions::goToPlayer, "Go to Player ...", KeyEvent.VK_P, MenuShortcuts.GO_TO_PLAYER);
result.addSeparator();
Menus.item(result, actions::zoomIn, "Zoom In", KeyEvent.VK_I, MenuShortcuts.ZOOM_IN);
Menus.item(result, actions::zoomOut, "Zoom Out", KeyEvent.VK_O, MenuShortcuts.ZOOM_OUT);
result.addSeparator();
savePlayerLocationsMenu =
Menus.item(result, actions::savePlayerLocations, "Save Player Locations", KeyEvent.VK_V, MenuShortcuts.SAVE_PLAYER_LOCATIONS);
savePlayerLocationsMenu.setEnabled(false);
reloadPlayerLocationsMenu =
Menus.item(result, actions::reloadPlayerLocations, "Reload Player Locations", KeyEvent.VK_R, MenuShortcuts.RELOAD_PLAYER_LOCATIONS);
reloadPlayerLocationsMenu.setEnabled(false);
Menus.item(result, actions::howCanIMoveAPlayer, "How Can I Move a Player?", KeyEvent.VK_M);
result.addSeparator();
Menus.item(result, actions::copySeedToClipboard, "Copy Seed to Clipboard", KeyEvent.VK_B, MenuShortcuts.COPY_SEED_TO_CLIPBOARD);
Menus.item(result, actions::takeScreenshot, "Take Screenshot ...", KeyEvent.VK_T, MenuShortcuts.TAKE_SCREENSHOT);
result.addSeparator();
Menus.item(result, actions::openExportDialog, "Export Biomes to Image ...", KeyEvent.VK_X, MenuShortcuts.EXPORT_BIOMES);
// @formatter:on
return result;
}
private JMenuItem create_Layers() {
JMenu result = new JMenu("Layers");
result.setMnemonic(KeyEvent.VK_L);
layersMenu = new LayersMenu(result, settings);
return result;
}
private JMenu create_Settings() {
JMenu result = new JMenu("Settings");
result.setMnemonic(KeyEvent.VK_S);
result.add(create_Settings_DefaultWorldType());
if (biomeProfileDirectory.isValid()) {
result.add(create_Settings_BiomeProfile());
}
result.addSeparator();
// @formatter:off
Menus.checkbox(result, settings.smoothScrolling, "Smooth Scrolling");
Menus.checkbox(result, settings.fragmentFading, "Fragment Fading");
Menus.checkbox(result, settings.maxZoom, "Restrict Maximum Zoom");
Menus.checkbox(result, settings.showFPS, "Show Framerate & CPU");
Menus.checkbox(result, settings.showScale, "Show Scale");
Menus.checkbox(result, settings.showDebug, "Show Debug Information");
Menus.checkbox(result, settings.useHybridScaling, "Use Hybrid Scaling");
// @formatter:on
result.addSeparator();
result.add(create_Settings_LookAndFeel());
result.add(create_Settings_Threads());
return result;
}
private JMenu create_Settings_DefaultWorldType() {
JMenu result = new JMenu("Default World Type");
// @formatter:off
Menus.radios(result, settings.worldType, WorldType.getWorldTypeSettingAvailableValues());
// @formatter:on
return result;
}
private JMenu create_Settings_LookAndFeel() {
JMenu result = new JMenu("Look & Feel");
List<AbstractButton> radios = new ArrayList<>();
Setting<AmidstLookAndFeel> lookAndFeelSetting = settings.lookAndFeel.withListener(
(oldValue, newValue) -> {
if (!oldValue.equals(newValue) && !actions.tryChangeLookAndFeel(newValue)) {
settings.lookAndFeel.set(oldValue);
radios.get(oldValue.ordinal()).setSelected(true);
}
});
radios.addAll(Menus.radios(result, lookAndFeelSetting, AmidstLookAndFeel.values()));
return result;
}
private JMenu create_Settings_Threads() {
UIManager.put("Slider.focus", UIManager.get("Slider.background"));
int cores = Runtime.getRuntime().availableProcessors();
JMenu submenu = new JMenu("No. of Threads");
JSlider slider = new JSlider(JSlider.VERTICAL, 1, cores, settings.threads.get());
submenu.add(slider);
slider.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
if (e.getSource() instanceof JSlider) {
if(settings.threads.get().intValue() != ((JSlider) e.getSource()).getValue()) {
settings.threads.set(((JSlider) e.getSource()).getValue());
MenuSelectionManager.defaultManager().clearSelectedPath();
actions.tryChangeThreads();
}
}
}
});
slider.setMinorTickSpacing(1);
slider.setPaintTicks(true);
slider.setSnapToTicks(true);
slider.setPaintLabels(true);
Hashtable<Integer, JLabel> table = new Hashtable<Integer, JLabel>(3);
table.put(1, new JLabel("1"));
table.put(cores / 2, new JLabel("" + cores / 2));
table.put(cores, new JLabel("" + cores));
slider.setLabelTable(table);
return submenu;
}
private JMenu create_Settings_BiomeProfile() {
JMenu result = new JMenu("Biome Profile");
// @formatter:off
new BiomeProfileMenuFactory(result, actions, biomeProfileDirectory, "Reload Biome Profiles", KeyEvent.VK_R, MenuShortcuts.RELOAD_BIOME_PROFILES,
"Create Example Profile", KeyEvent.VK_C);
// @formatter:on
return result;
}
private JMenu create_Help() {
JMenu result = new JMenu("Help");
result.setMnemonic(KeyEvent.VK_H);
// @formatter:off
Menus.item(result, actions::displayLogMessages, "Display Log Messages ...", KeyEvent.VK_M);
Menus.item(result, actions::checkForUpdates, "Check for Updates ...", KeyEvent.VK_U);
Menus.item(result, actions::viewLicense, "View Licenses ...", KeyEvent.VK_L);
Menus.item(result, actions::about, "About ...", KeyEvent.VK_A);
// @formatter:on
return result;
}
}
|
amidst
|
src\main\java\amidst\gui\main\menu\BiomeProfileMenuFactory.java
|
package amidst.gui.main.menu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.KeyStroke;
import amidst.documentation.NotThreadSafe;
import amidst.gui.main.Actions;
import amidst.logging.AmidstLogger;
import amidst.settings.biomeprofile.BiomeProfile;
import amidst.settings.biomeprofile.BiomeProfileDirectory;
import amidst.settings.biomeprofile.BiomeProfileVisitor;
@NotThreadSafe
public class BiomeProfileMenuFactory {
@NotThreadSafe
private static class BiomeProfileVisitorImpl implements BiomeProfileVisitor {
private final List<JCheckBoxMenuItem> allCheckBoxes = new ArrayList<>();
private final List<JMenu> menuStack = new ArrayList<>();
private Runnable defaultBiomeProfileSelector;
private boolean isFirstContainer = true;
private final Actions actions;
private BiomeProfileVisitorImpl(JMenu parentMenu, Actions actions) {
this.actions = actions;
menuStack.add(parentMenu);
}
@Override
public void enterDirectory(String name) {
if (isFirstContainer) {
isFirstContainer = false;
} else {
JMenu newMenu = new JMenu(name);
getLastMenu().add(newMenu);
menuStack.add(newMenu);
}
}
@Override
public void visitProfile(BiomeProfile profile) {
JCheckBoxMenuItem checkBox = createCheckBox(profile);
allCheckBoxes.add(checkBox);
getLastMenu().add(checkBox);
}
@Override
public void leaveDirectory() {
removeLastMenu();
}
private JMenu getLastMenu() {
return menuStack.get(menuStack.size() - 1);
}
private void removeLastMenu() {
menuStack.remove(menuStack.size() - 1);
}
private JCheckBoxMenuItem createCheckBox(BiomeProfile profile) {
JCheckBoxMenuItem result = new JCheckBoxMenuItem(profile.getName());
tryCreateKeyboardShortcut(profile.getShortcut(), result);
result.addActionListener(createListener(profile, result));
return result;
}
private void tryCreateKeyboardShortcut(String shortcut, JCheckBoxMenuItem checkBox) {
if (shortcut != null) {
KeyStroke accelerator = KeyStroke.getKeyStroke(shortcut);
if (accelerator != null) {
checkBox.setAccelerator(accelerator);
} else {
AmidstLogger.info("Unable to create keyboard shortcut from: " + shortcut);
}
}
}
private ActionListener createListener(final BiomeProfile profile, final JCheckBoxMenuItem selectedCheckBox) {
ActionListener result = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
actions.selectBiomeProfile(profile);
for (JCheckBoxMenuItem checkBox : allCheckBoxes) {
checkBox.setSelected(false);
}
selectedCheckBox.setSelected(true);
}
};
if (defaultBiomeProfileSelector == null && profile.equals(BiomeProfile.getDefaultProfile())) {
defaultBiomeProfileSelector = () -> result.actionPerformed(null);
}
return result;
}
public void selectDefaultBiomeProfile() {
if (defaultBiomeProfileSelector != null) {
defaultBiomeProfileSelector.run();
}
}
}
private final JMenu parentMenu;
private final Actions actions;
private final BiomeProfileDirectory biomeProfileDirectory;
private final String reloadText;
private final int reloadMnemonic;
private final MenuShortcut reloadMenuShortcut;
private final String createExampleText;
private final int createExampleMnemonic;
public BiomeProfileMenuFactory(
JMenu parentMenu,
Actions actions,
BiomeProfileDirectory biomeProfileDirectory,
String reloadText,
int reloadMnemonic,
MenuShortcut reloadMenuShortcut,
String createExampleText,
int createExampleMnemonic) {
this.parentMenu = parentMenu;
this.actions = actions;
this.biomeProfileDirectory = biomeProfileDirectory;
this.reloadText = reloadText;
this.reloadMnemonic = reloadMnemonic;
this.reloadMenuShortcut = reloadMenuShortcut;
this.createExampleText = createExampleText;
this.createExampleMnemonic = createExampleMnemonic;
AmidstLogger.info("Checking for additional biome profiles.");
initParentMenu();
}
private void initParentMenu() {
parentMenu.removeAll();
BiomeProfileVisitorImpl visitor = new BiomeProfileVisitorImpl(parentMenu, actions);
visitor.visitProfile(BiomeProfile.getDefaultProfile());
parentMenu.addSeparator();
if (biomeProfileDirectory.visitProfiles(visitor)) {
parentMenu.addSeparator();
}
Menus.item(parentMenu, this::doReload, reloadText, reloadMnemonic, reloadMenuShortcut);
Menus.item(parentMenu, this::doCreateExampleProfile, createExampleText, createExampleMnemonic);
visitor.selectDefaultBiomeProfile();
}
private void doCreateExampleProfile() {
actions.createExampleProfile(biomeProfileDirectory);
doReload();
}
private void doReload() {
AmidstLogger.info("Reloading additional biome profiles.");
initParentMenu();
}
}
|
amidst
|
src\main\java\amidst\gui\main\menu\LayersMenu.java
|
package amidst.gui.main.menu;
import java.util.LinkedList;
import java.util.List;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import amidst.AmidstSettings;
import amidst.ResourceLoader;
import amidst.documentation.AmidstThread;
import amidst.documentation.CalledOnlyBy;
import amidst.documentation.NotThreadSafe;
import amidst.fragment.layer.LayerIds;
import amidst.gui.main.viewer.ViewerFacade;
import amidst.mojangapi.world.Dimension;
import amidst.settings.Setting;
@NotThreadSafe
public class LayersMenu {
private final JMenu menu;
private final AmidstSettings settings;
private final Setting<Dimension> dimensionSetting;
private final List<JMenuItem> overworldMenuItems = new LinkedList<>();
private final List<JMenuItem> endMenuItems = new LinkedList<>();
private volatile ViewerFacade viewerFacade;
@CalledOnlyBy(AmidstThread.EDT)
public LayersMenu(JMenu menu, AmidstSettings settings) {
this.menu = menu;
this.settings = settings;
this.dimensionSetting = settings.dimension
.withListener((oldValue, newValue) -> this.createMenu(newValue));
}
@CalledOnlyBy(AmidstThread.EDT)
public void init(ViewerFacade viewerFacade) {
this.viewerFacade = viewerFacade;
if (viewerFacade != null) {
createMenu(dimensionSetting.get());
} else {
disable();
}
}
@CalledOnlyBy(AmidstThread.EDT)
private void createMenu(Dimension selectedDimension) {
menu.removeAll();
overworldMenuItems.clear();
endMenuItems.clear();
createDimensionLayers(selectedDimension);
menu.setEnabled(true);
}
@CalledOnlyBy(AmidstThread.EDT)
private void createDimensionLayers(Dimension dimension) {
if (viewerFacade.hasLayer(LayerIds.END_ISLANDS)) {
createAllDimensions();
menu.addSeparator();
createOverworldAndEndLayers(dimension);
} else if (!dimension.equals(Dimension.OVERWORLD)) {
dimensionSetting.set(Dimension.OVERWORLD);
} else {
createAllDimensions();
menu.addSeparator();
createOverworldLayers(dimension);
}
}
@CalledOnlyBy(AmidstThread.EDT)
private void createOverworldAndEndLayers(Dimension dimension) {
// @formatter:off
ButtonGroup group = new ButtonGroup();
Menus.radio( menu, dimensionSetting, group, Dimension.OVERWORLD, MenuShortcuts.DISPLAY_DIMENSION_OVERWORLD);
createOverworldLayers(dimension);
menu.addSeparator();
Menus.radio( menu, dimensionSetting, group, Dimension.END, MenuShortcuts.DISPLAY_DIMENSION_END);
endLayer( settings.showEndCities, "End City Icons", getIcon("end_city.png"), MenuShortcuts.SHOW_END_CITIES, dimension, LayerIds.END_CITY);
// @formatter:on
}
@CalledOnlyBy(AmidstThread.EDT)
private void createOverworldLayers(Dimension dimension) {
// @formatter:off
overworldLayer(settings.showSlimeChunks, "Slime Chunks", getIcon("slime.png"), MenuShortcuts.SHOW_SLIME_CHUNKS, dimension, LayerIds.SLIME);
overworldLayer(settings.showSpawn, "Spawn Location Icon", getIcon("spawn.png"), MenuShortcuts.SHOW_WORLD_SPAWN, dimension, LayerIds.SPAWN);
overworldLayer(settings.showStrongholds, "Stronghold Icons", getIcon("stronghold.png"), MenuShortcuts.SHOW_STRONGHOLDS, dimension, LayerIds.STRONGHOLD);
overworldLayer(settings.showVillages, "Village/Outpost Icons", getIcon("village.png"), MenuShortcuts.SHOW_VILLAGES, dimension, LayerIds.VILLAGE);
overworldLayer(settings.showTemples, "Temple/Witch Hut Icons", getIcon("desert.png"), MenuShortcuts.SHOW_TEMPLES, dimension, LayerIds.TEMPLE);
overworldLayer(settings.showMineshafts, "Mineshaft Icons", getIcon("mineshaft.png"), MenuShortcuts.SHOW_MINESHAFTS, dimension, LayerIds.MINESHAFT);
overworldLayer(settings.showOceanMonuments, "Ocean Monument Icons", getIcon("ocean_monument.png"), MenuShortcuts.SHOW_OCEAN_MONUMENTS, dimension, LayerIds.OCEAN_MONUMENT);
overworldLayer(settings.showWoodlandMansions, "Woodland Mansion Icons", getIcon("woodland_mansion.png"),MenuShortcuts.SHOW_WOODLAND_MANSIONS, dimension, LayerIds.WOODLAND_MANSION);
overworldLayer(settings.showOceanFeatures, "Ocean Features Icons", getIcon("shipwreck.png"), MenuShortcuts.SHOW_OCEAN_FEATURES, dimension, LayerIds.OCEAN_FEATURES);
overworldLayer(settings.showNetherFortresses, "Nether Features Icons", getIcon("nether_fortress.png"), MenuShortcuts.SHOW_NETHER_FEATURES, dimension, LayerIds.NETHER_FEATURES);
// @formatter:on
}
@CalledOnlyBy(AmidstThread.EDT)
private void createAllDimensions() {
// @formatter:off
Menus.checkbox(menu, settings.showGrid, "Grid", getIcon("grid.png"), MenuShortcuts.SHOW_GRID);
Menus.checkbox(menu, settings.showPlayers, "Player Icons", getIcon("player.png"), MenuShortcuts.SHOW_PLAYERS);
// @formatter:on
}
@CalledOnlyBy(AmidstThread.EDT)
public void overworldLayer(
Setting<Boolean> setting,
String text,
ImageIcon icon,
MenuShortcut menuShortcut,
Dimension dimension,
int layerId) {
overworldMenuItems.add(createLayer(setting, text, icon, menuShortcut, dimension, layerId));
}
@CalledOnlyBy(AmidstThread.EDT)
public void endLayer(
Setting<Boolean> setting,
String text,
ImageIcon icon,
MenuShortcut menuShortcut,
Dimension dimension,
int layerId) {
endMenuItems.add(createLayer(setting, text, icon, menuShortcut, dimension, layerId));
}
@CalledOnlyBy(AmidstThread.EDT)
private JCheckBoxMenuItem createLayer(
Setting<Boolean> setting,
String text,
ImageIcon icon,
MenuShortcut menuShortcut,
Dimension dimension,
int layerId) {
return Menus.checkbox(menu, setting, text, icon, menuShortcut);
}
@CalledOnlyBy(AmidstThread.EDT)
public void disable() {
this.viewerFacade = null;
menu.setEnabled(false);
}
@CalledOnlyBy(AmidstThread.EDT)
private ImageIcon getIcon(String icon) {
return new ImageIcon(ResourceLoader.getImage("/amidst/gui/main/icon/" + icon));
}
}
|
amidst
|
src\main\java\amidst\gui\main\menu\Menus.java
|
package amidst.gui.main.menu;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import amidst.documentation.Immutable;
import amidst.settings.Setting;
/**
* This creates only a one way data binding. If the setting is updated, this
* will not be reflected on the UI. However, this should be good enough for
* Amidst, since the Settings are only updated via the menu.
*/
@Immutable
public enum Menus {
;
public static <T> List<JRadioButtonMenuItem> radios(JMenu menu, Setting<T> setting,
@SuppressWarnings("unchecked") T... values) {
Objects.requireNonNull(values);
ButtonGroup group = new ButtonGroup();
List<JRadioButtonMenuItem> radios = new ArrayList<>(values.length);
for (T value : values) {
radios.add(radio(menu, setting, group, value));
}
return radios;
}
public static <T> JRadioButtonMenuItem radio(JMenu menu, Setting<T> setting, ButtonGroup group, T value) {
JRadioButtonMenuItem menuItem = new JRadioButtonMenuItem(value.toString());
return radio(menu, setting, group, menuItem, value);
}
public static <T> JRadioButtonMenuItem radio(
JMenu menu,
Setting<T> setting,
ButtonGroup group,
T value,
ImageIcon icon) {
JRadioButtonMenuItem menuItem = new JRadioButtonMenuItem(value.toString(), icon);
return radio(menu, setting, group, menuItem, value);
}
public static <T> JRadioButtonMenuItem radio(
JMenu menu,
Setting<T> setting,
ButtonGroup group,
T value,
MenuShortcut menuShortcut) {
JRadioButtonMenuItem menuItem = new JRadioButtonMenuItem(value.toString());
menuItem.setAccelerator(menuShortcut.getKeyStroke());
return radio(menu, setting, group, menuItem, value);
}
public static <T> JRadioButtonMenuItem radio(
JMenu menu,
Setting<T> setting,
ButtonGroup group,
T value,
ImageIcon icon,
MenuShortcut menuShortcut) {
JRadioButtonMenuItem menuItem = new JRadioButtonMenuItem(value.toString(), icon);
menuItem.setAccelerator(menuShortcut.getKeyStroke());
return radio(menu, setting, group, menuItem, value);
}
private static <T> JRadioButtonMenuItem radio(
JMenu menu,
Setting<T> setting,
ButtonGroup group,
JRadioButtonMenuItem menuItem,
T value) {
Objects.requireNonNull(value);
menuItem.addActionListener(e -> setting.set(value));
menuItem.setSelected(value.equals(setting.get()));
group.add(menuItem);
menu.add(menuItem);
return menuItem;
}
public static JCheckBoxMenuItem checkbox(JMenu menu, Setting<Boolean> setting, String text) {
return checkbox(menu, setting, new JCheckBoxMenuItem(text));
}
public static JCheckBoxMenuItem checkbox(JMenu menu, Setting<Boolean> setting, String text, ImageIcon icon) {
return checkbox(menu, setting, new JCheckBoxMenuItem(text, icon));
}
public static JCheckBoxMenuItem checkbox(
JMenu menu,
Setting<Boolean> setting,
String text,
MenuShortcut menuShortcut) {
JCheckBoxMenuItem menuItem = new JCheckBoxMenuItem(text);
menuItem.setAccelerator(menuShortcut.getKeyStroke());
return checkbox(menu, setting, menuItem);
}
public static JCheckBoxMenuItem checkbox(
JMenu menu,
Setting<Boolean> setting,
String text,
ImageIcon icon,
MenuShortcut menuShortcut) {
JCheckBoxMenuItem menuItem = new JCheckBoxMenuItem(text, icon);
menuItem.setAccelerator(menuShortcut.getKeyStroke());
return checkbox(menu, setting, menuItem);
}
private static JCheckBoxMenuItem checkbox(JMenu menu, Setting<Boolean> setting, JCheckBoxMenuItem menuItem) {
menuItem.setSelected(setting.get());
menuItem.addActionListener(e -> setting.set(menuItem.isSelected()));
menu.add(menuItem);
return menuItem;
}
public static JMenuItem item(JMenu menu, Runnable runnable, String text, int mnemonic) {
JMenuItem menuItem = new JMenuItem(text);
return item(menu, runnable, menuItem, mnemonic);
}
public static JMenuItem item(JMenu menu, Runnable runnable, String text, int mnemonic, MenuShortcut menuShortcut) {
JMenuItem menuItem = new JMenuItem(text);
menuItem.setAccelerator(menuShortcut.getKeyStroke());
return item(menu, runnable, menuItem, mnemonic);
}
private static JMenuItem item(JMenu menu, Runnable runnable, JMenuItem menuItem, int mnemonic) {
menuItem.setMnemonic(mnemonic);
menuItem.addActionListener(e -> runnable.run());
menu.add(menuItem);
return menuItem;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.