Clean up
- Added final keyword wherever possible - Improved some font code
This commit is contained in:
@@ -16,7 +16,6 @@ import mightypork.rogue.gui.screens.test_cat_sound.ScreenTestCat;
|
|||||||
import mightypork.rogue.gui.screens.test_font.ScreenTestFont;
|
import mightypork.rogue.gui.screens.test_font.ScreenTestFont;
|
||||||
import mightypork.rogue.input.InputSystem;
|
import mightypork.rogue.input.InputSystem;
|
||||||
import mightypork.rogue.input.KeyStroke;
|
import mightypork.rogue.input.KeyStroke;
|
||||||
import mightypork.rogue.loading.DeferredLoader;
|
|
||||||
import mightypork.rogue.render.DisplaySystem;
|
import mightypork.rogue.render.DisplaySystem;
|
||||||
import mightypork.rogue.sound.SoundSystem;
|
import mightypork.rogue.sound.SoundSystem;
|
||||||
import mightypork.utils.control.bus.EventBus;
|
import mightypork.utils.control.bus.EventBus;
|
||||||
@@ -62,7 +61,7 @@ public class App implements AppAccess {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
inst.start();
|
inst.start();
|
||||||
} catch (Throwable t) {
|
} catch (final Throwable t) {
|
||||||
onCrash(t);
|
onCrash(t);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -124,7 +123,7 @@ public class App implements AppAccess {
|
|||||||
/*
|
/*
|
||||||
* Setup logging
|
* Setup logging
|
||||||
*/
|
*/
|
||||||
LogInstance log = Log.create("runtime", Paths.LOGS, 10);
|
final LogInstance log = Log.create("runtime", Paths.LOGS, 10);
|
||||||
log.enable(Config.LOGGING_ENABLED);
|
log.enable(Config.LOGGING_ENABLED);
|
||||||
log.enableSysout(Config.LOG_TO_STDOUT);
|
log.enableSysout(Config.LOG_TO_STDOUT);
|
||||||
|
|
||||||
@@ -153,14 +152,6 @@ public class App implements AppAccess {
|
|||||||
soundSystem = new SoundSystem(this);
|
soundSystem = new SoundSystem(this);
|
||||||
soundSystem.setMasterVolume(1);
|
soundSystem.setMasterVolume(1);
|
||||||
|
|
||||||
/*
|
|
||||||
* Load resources
|
|
||||||
*/
|
|
||||||
Log.f1("Registering resources...");
|
|
||||||
bus().subscribe(new DeferredLoader(this));
|
|
||||||
|
|
||||||
Res.load(this);
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Input
|
* Input
|
||||||
*/
|
*/
|
||||||
@@ -168,6 +159,13 @@ public class App implements AppAccess {
|
|||||||
inputSystem = new InputSystem(this);
|
inputSystem = new InputSystem(this);
|
||||||
setupGlobalKeystrokes();
|
setupGlobalKeystrokes();
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Load resources
|
||||||
|
*/
|
||||||
|
Log.f1("Loading resources...");
|
||||||
|
|
||||||
|
Res.load(this);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Screen registry
|
* Screen registry
|
||||||
*/
|
*/
|
||||||
@@ -179,7 +177,7 @@ public class App implements AppAccess {
|
|||||||
* Prepare main loop
|
* Prepare main loop
|
||||||
*/
|
*/
|
||||||
Log.f1("Preparing main loop...");
|
Log.f1("Preparing main loop...");
|
||||||
ArrayList<Runnable> loopTasks = new ArrayList<Runnable>();
|
final ArrayList<Runnable> loopTasks = new ArrayList<Runnable>();
|
||||||
|
|
||||||
loopTasks.add(new Runnable() {
|
loopTasks.add(new Runnable() {
|
||||||
|
|
||||||
@@ -304,7 +302,7 @@ public class App implements AppAccess {
|
|||||||
fileLock.release();
|
fileLock.release();
|
||||||
randomAccessFile.close();
|
randomAccessFile.close();
|
||||||
lockFile.delete();
|
lockFile.delete();
|
||||||
} catch (Exception e) {
|
} catch (final Exception e) {
|
||||||
System.err.println("Unable to remove lock file.");
|
System.err.println("Unable to remove lock file.");
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
@@ -313,7 +311,7 @@ public class App implements AppAccess {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (final Exception e) {
|
||||||
System.err.println("Unable to create and/or lock file.");
|
System.err.println("Unable to create and/or lock file.");
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import mightypork.utils.control.bus.EventBus;
|
|||||||
*/
|
*/
|
||||||
public class AppAdapter implements AppAccess {
|
public class AppAdapter implements AppAccess {
|
||||||
|
|
||||||
private AppAccess app;
|
private final AppAccess app;
|
||||||
|
|
||||||
|
|
||||||
public AppAdapter(AppAccess app) {
|
public AppAdapter(AppAccess app) {
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ public class Config {
|
|||||||
{
|
{
|
||||||
Log.f2("Initializing configuration manager.");
|
Log.f2("Initializing configuration manager.");
|
||||||
|
|
||||||
String comment = Const.APP_NAME + " config file";
|
final String comment = Const.APP_NAME + " config file";
|
||||||
|
|
||||||
mgr = new PropertyManager(Paths.CONFIG, comment);
|
mgr = new PropertyManager(Paths.CONFIG, comment);
|
||||||
|
|
||||||
@@ -76,7 +76,6 @@ public class Config {
|
|||||||
public static boolean LOG_TO_STDOUT = true;
|
public static boolean LOG_TO_STDOUT = true;
|
||||||
public static boolean SINGLE_INSTANCE = true;
|
public static boolean SINGLE_INSTANCE = true;
|
||||||
|
|
||||||
public static boolean LOG_FONTS = false;
|
|
||||||
public static boolean LOG_BUS = false;
|
public static boolean LOG_BUS = false;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,8 +18,8 @@ import mightypork.utils.control.timing.TimerDelta;
|
|||||||
|
|
||||||
public class MainLoop extends Subsystem implements ActionRequest.Listener, MainLoopTaskRequest.Listener {
|
public class MainLoop extends Subsystem implements ActionRequest.Listener, MainLoopTaskRequest.Listener {
|
||||||
|
|
||||||
private Queue<Runnable> taskQueue = new ConcurrentLinkedQueue<Runnable>();
|
private final Queue<Runnable> taskQueue = new ConcurrentLinkedQueue<Runnable>();
|
||||||
private List<Runnable> regularTasks;
|
private final List<Runnable> regularTasks;
|
||||||
|
|
||||||
|
|
||||||
public MainLoop(App app, ArrayList<Runnable> loopTasks) {
|
public MainLoop(App app, ArrayList<Runnable> loopTasks) {
|
||||||
@@ -42,7 +42,7 @@ public class MainLoop extends Subsystem implements ActionRequest.Listener, MainL
|
|||||||
|
|
||||||
bus().send(new UpdateEvent(timer.getDelta()));
|
bus().send(new UpdateEvent(timer.getDelta()));
|
||||||
|
|
||||||
for (Runnable r : regularTasks) {
|
for (final Runnable r : regularTasks) {
|
||||||
r.run();
|
r.run();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,7 +113,7 @@ public class MainLoop extends Subsystem implements ActionRequest.Listener, MainL
|
|||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void queueTask(Runnable request)
|
public synchronized void queueTask(Runnable request)
|
||||||
{
|
{
|
||||||
taskQueue.add(request);
|
taskQueue.add(request);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,13 +5,14 @@ import mightypork.rogue.fonts.DeferredFont;
|
|||||||
import mightypork.rogue.fonts.DeferredFont.FontStyle;
|
import mightypork.rogue.fonts.DeferredFont.FontStyle;
|
||||||
import mightypork.rogue.fonts.FontBank;
|
import mightypork.rogue.fonts.FontBank;
|
||||||
import mightypork.rogue.fonts.GLFont;
|
import mightypork.rogue.fonts.GLFont;
|
||||||
|
import mightypork.rogue.loading.AsyncResourceLoader;
|
||||||
import mightypork.rogue.sound.SoundBank;
|
import mightypork.rogue.sound.SoundBank;
|
||||||
import mightypork.rogue.sound.players.EffectPlayer;
|
import mightypork.rogue.sound.players.EffectPlayer;
|
||||||
import mightypork.rogue.sound.players.LoopPlayer;
|
import mightypork.rogue.sound.players.LoopPlayer;
|
||||||
import mightypork.rogue.texture.FilteredTexture.Filter;
|
import mightypork.rogue.textures.TextureBank;
|
||||||
import mightypork.rogue.texture.FilteredTexture.Wrap;
|
import mightypork.rogue.textures.TxQuad;
|
||||||
import mightypork.rogue.texture.TextureBank;
|
import mightypork.rogue.textures.FilteredTexture.Filter;
|
||||||
import mightypork.rogue.texture.TxQuad;
|
import mightypork.rogue.textures.FilteredTexture.Wrap;
|
||||||
|
|
||||||
import org.newdawn.slick.opengl.Texture;
|
import org.newdawn.slick.opengl.Texture;
|
||||||
|
|
||||||
@@ -40,6 +41,8 @@ public class Res {
|
|||||||
if (initialized) return;
|
if (initialized) return;
|
||||||
initialized = true;
|
initialized = true;
|
||||||
|
|
||||||
|
AsyncResourceLoader.launch(app);
|
||||||
|
|
||||||
textures = new TextureBank(app);
|
textures = new TextureBank(app);
|
||||||
sounds = new SoundBank(app);
|
sounds = new SoundBank(app);
|
||||||
fonts = new FontBank(app);
|
fonts = new FontBank(app);
|
||||||
|
|||||||
@@ -10,7 +10,8 @@ import mightypork.utils.control.bus.SingularEvent;
|
|||||||
*
|
*
|
||||||
* @author MightyPork
|
* @author MightyPork
|
||||||
*/
|
*/
|
||||||
public class ActionRequest implements Event<ActionRequest.Listener>, SingularEvent {
|
@SingularEvent
|
||||||
|
public class ActionRequest implements Event<ActionRequest.Listener> {
|
||||||
|
|
||||||
private final RequestType type;
|
private final RequestType type;
|
||||||
|
|
||||||
@@ -33,7 +34,7 @@ public class ActionRequest implements Event<ActionRequest.Listener>, SingularEve
|
|||||||
*
|
*
|
||||||
* @param request
|
* @param request
|
||||||
*/
|
*/
|
||||||
public void requestAction(RequestType request);
|
void requestAction(RequestType request);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static enum RequestType
|
public static enum RequestType
|
||||||
|
|||||||
@@ -74,7 +74,7 @@ public class KeyboardEvent implements Event<KeyboardEvent.Listener> {
|
|||||||
*
|
*
|
||||||
* @param event event
|
* @param event event
|
||||||
*/
|
*/
|
||||||
public void receive(KeyboardEvent event);
|
void receive(KeyboardEvent event);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,8 @@ import mightypork.utils.control.bus.SingularEvent;
|
|||||||
*
|
*
|
||||||
* @author MightyPork
|
* @author MightyPork
|
||||||
*/
|
*/
|
||||||
public class MainLoopTaskRequest implements Event<MainLoopTaskRequest.Listener>, SingularEvent {
|
@SingularEvent
|
||||||
|
public class MainLoopTaskRequest implements Event<MainLoopTaskRequest.Listener> {
|
||||||
|
|
||||||
private final Runnable task;
|
private final Runnable task;
|
||||||
|
|
||||||
@@ -33,6 +34,6 @@ public class MainLoopTaskRequest implements Event<MainLoopTaskRequest.Listener>,
|
|||||||
*
|
*
|
||||||
* @param request
|
* @param request
|
||||||
*/
|
*/
|
||||||
public void queueTask(Runnable request);
|
void queueTask(Runnable request);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import mightypork.utils.math.coord.Coord;
|
|||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mouse button / wheel event
|
* Mouse button / wheel event triggered
|
||||||
*
|
*
|
||||||
* @author MightyPork
|
* @author MightyPork
|
||||||
*/
|
*/
|
||||||
@@ -114,6 +114,6 @@ public class MouseButtonEvent implements Event<MouseButtonEvent.Listener> {
|
|||||||
*
|
*
|
||||||
* @param event event
|
* @param event event
|
||||||
*/
|
*/
|
||||||
public void receive(MouseButtonEvent event);
|
void receive(MouseButtonEvent event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,11 @@ import mightypork.utils.control.bus.Event;
|
|||||||
import mightypork.utils.math.coord.Coord;
|
import mightypork.utils.math.coord.Coord;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mouse moved
|
||||||
|
*
|
||||||
|
* @author MightyPork
|
||||||
|
*/
|
||||||
public class MouseMotionEvent implements Event<MouseMotionEvent.Listener> {
|
public class MouseMotionEvent implements Event<MouseMotionEvent.Listener> {
|
||||||
|
|
||||||
private final Coord move;
|
private final Coord move;
|
||||||
@@ -48,7 +53,7 @@ public class MouseMotionEvent implements Event<MouseMotionEvent.Listener> {
|
|||||||
*
|
*
|
||||||
* @param event event
|
* @param event event
|
||||||
*/
|
*/
|
||||||
public void receive(MouseMotionEvent event);
|
void receive(MouseMotionEvent event);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
package mightypork.rogue.bus.events;
|
package mightypork.rogue.bus.events;
|
||||||
|
|
||||||
|
|
||||||
import mightypork.rogue.loading.Deferred;
|
import mightypork.rogue.loading.DeferredResource;
|
||||||
import mightypork.utils.control.bus.Event;
|
import mightypork.utils.control.bus.Event;
|
||||||
import mightypork.utils.control.bus.SingularEvent;
|
import mightypork.utils.control.bus.SingularEvent;
|
||||||
|
|
||||||
@@ -11,12 +11,13 @@ import mightypork.utils.control.bus.SingularEvent;
|
|||||||
*
|
*
|
||||||
* @author MightyPork
|
* @author MightyPork
|
||||||
*/
|
*/
|
||||||
public class ResourceLoadRequest implements Event<ResourceLoadRequest.Listener>, SingularEvent {
|
@SingularEvent
|
||||||
|
public class ResourceLoadRequest implements Event<ResourceLoadRequest.Listener> {
|
||||||
|
|
||||||
private final Deferred resource;
|
private final DeferredResource resource;
|
||||||
|
|
||||||
|
|
||||||
public ResourceLoadRequest(Deferred resource) {
|
public ResourceLoadRequest(DeferredResource resource) {
|
||||||
this.resource = resource;
|
this.resource = resource;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,6 +35,6 @@ public class ResourceLoadRequest implements Event<ResourceLoadRequest.Listener>,
|
|||||||
*
|
*
|
||||||
* @param resource
|
* @param resource
|
||||||
*/
|
*/
|
||||||
public void loadResource(Deferred resource);
|
void loadResource(DeferredResource resource);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -45,6 +45,6 @@ public class ScreenChangeEvent implements Event<ScreenChangeEvent.Listener> {
|
|||||||
|
|
||||||
public interface Listener {
|
public interface Listener {
|
||||||
|
|
||||||
public void receive(ScreenChangeEvent event);
|
void receive(ScreenChangeEvent event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,13 @@ import mightypork.utils.control.bus.Event;
|
|||||||
import mightypork.utils.control.bus.SingularEvent;
|
import mightypork.utils.control.bus.SingularEvent;
|
||||||
|
|
||||||
|
|
||||||
public class ScreenRequestEvent implements Event<ScreenRequestEvent.Listener>, SingularEvent {
|
/**
|
||||||
|
* Request to change screen
|
||||||
|
*
|
||||||
|
* @author MightyPork
|
||||||
|
*/
|
||||||
|
@SingularEvent
|
||||||
|
public class ScreenRequestEvent implements Event<ScreenRequestEvent.Listener> {
|
||||||
|
|
||||||
private final String scrName;
|
private final String scrName;
|
||||||
|
|
||||||
@@ -23,7 +29,7 @@ public class ScreenRequestEvent implements Event<ScreenRequestEvent.Listener>, S
|
|||||||
|
|
||||||
public interface Listener {
|
public interface Listener {
|
||||||
|
|
||||||
public void showScreen(String key);
|
void showScreen(String key);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import java.awt.FontFormatException;
|
|||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
|
|
||||||
import mightypork.rogue.loading.DeferredResource;
|
import mightypork.rogue.loading.BaseDeferredResource;
|
||||||
import mightypork.rogue.loading.MustLoadInMainThread;
|
import mightypork.rogue.loading.MustLoadInMainThread;
|
||||||
import mightypork.utils.files.FileUtils;
|
import mightypork.utils.files.FileUtils;
|
||||||
import mightypork.utils.math.color.RGB;
|
import mightypork.utils.math.color.RGB;
|
||||||
@@ -18,7 +18,8 @@ import mightypork.utils.math.coord.Coord;
|
|||||||
*
|
*
|
||||||
* @author MightyPork
|
* @author MightyPork
|
||||||
*/
|
*/
|
||||||
public class DeferredFont extends DeferredResource implements MustLoadInMainThread, GLFont {
|
@MustLoadInMainThread
|
||||||
|
public class DeferredFont extends BaseDeferredResource implements GLFont {
|
||||||
|
|
||||||
public static enum FontStyle
|
public static enum FontStyle
|
||||||
{
|
{
|
||||||
@@ -44,7 +45,7 @@ public class DeferredFont extends DeferredResource implements MustLoadInMainThre
|
|||||||
*
|
*
|
||||||
* @param resourcePath resource to load
|
* @param resourcePath resource to load
|
||||||
* @param extraChars extra chars (0-255 loaded by default)
|
* @param extraChars extra chars (0-255 loaded by default)
|
||||||
* @param size size (pt)
|
* @param size size (px)
|
||||||
*/
|
*/
|
||||||
public DeferredFont(String resourcePath, String extraChars, double size) {
|
public DeferredFont(String resourcePath, String extraChars, double size) {
|
||||||
this(resourcePath, extraChars, size, FontStyle.PLAIN, true);
|
this(resourcePath, extraChars, size, FontStyle.PLAIN, true);
|
||||||
@@ -85,7 +86,7 @@ public class DeferredFont extends DeferredResource implements MustLoadInMainThre
|
|||||||
@Override
|
@Override
|
||||||
protected final void loadResource(String path) throws FontFormatException, IOException
|
protected final void loadResource(String path) throws FontFormatException, IOException
|
||||||
{
|
{
|
||||||
Font awtFont = getAwtFont(path, (float) size, style.numeric);
|
final Font awtFont = getAwtFont(path, (float) size, style.numeric);
|
||||||
|
|
||||||
font = new SlickFont(awtFont, antiAlias, extraChars);
|
font = new SlickFont(awtFont, antiAlias, extraChars);
|
||||||
}
|
}
|
||||||
@@ -119,7 +120,7 @@ public class DeferredFont extends DeferredResource implements MustLoadInMainThre
|
|||||||
} finally {
|
} finally {
|
||||||
try {
|
try {
|
||||||
if (in != null) in.close();
|
if (in != null) in.close();
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
//pass
|
//pass
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ public class FontBank extends AppAdapter {
|
|||||||
*/
|
*/
|
||||||
public GLFont getFont(String key)
|
public GLFont getFont(String key)
|
||||||
{
|
{
|
||||||
GLFont f = fonts.get(key);
|
final GLFont f = fonts.get(key);
|
||||||
|
|
||||||
if (f == null) {
|
if (f == null) {
|
||||||
Log.w("There's no font called " + key + "!");
|
Log.w("There's no font called " + key + "!");
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ public interface GLFont {
|
|||||||
* @param text string to draw
|
* @param text string to draw
|
||||||
* @param color draw color
|
* @param color draw color
|
||||||
*/
|
*/
|
||||||
abstract void draw(String text, RGB color);
|
void draw(String text, RGB color);
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -24,7 +24,7 @@ public interface GLFont {
|
|||||||
* @param startIndex first drawn character index
|
* @param startIndex first drawn character index
|
||||||
* @param endIndex last drawn character index
|
* @param endIndex last drawn character index
|
||||||
*/
|
*/
|
||||||
abstract void draw(String text, RGB color, int startIndex, int endIndex);
|
void draw(String text, RGB color, int startIndex, int endIndex);
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -32,7 +32,7 @@ public interface GLFont {
|
|||||||
*
|
*
|
||||||
* @param str string to draw
|
* @param str string to draw
|
||||||
*/
|
*/
|
||||||
abstract void draw(String str);
|
void draw(String str);
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -41,19 +41,19 @@ public interface GLFont {
|
|||||||
* @param text string to check
|
* @param text string to check
|
||||||
* @return coord (width, height)
|
* @return coord (width, height)
|
||||||
*/
|
*/
|
||||||
abstract Coord getNeededSpace(String text);
|
Coord getNeededSpace(String text);
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return font height
|
* @return font height
|
||||||
*/
|
*/
|
||||||
abstract int getHeight();
|
int getHeight();
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param text texted text
|
* @param text texted text
|
||||||
* @return space needed
|
* @return space needed
|
||||||
*/
|
*/
|
||||||
abstract int getWidth(String text);
|
int getWidth(String text);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,8 +39,8 @@ public class SlickFont implements GLFont {
|
|||||||
{
|
{
|
||||||
if (chars == null) return null;
|
if (chars == null) return null;
|
||||||
|
|
||||||
StringBuilder sb = new StringBuilder();
|
final StringBuilder sb = new StringBuilder();
|
||||||
for (char c : chars.toCharArray()) {
|
for (final char c : chars.toCharArray()) {
|
||||||
if (c <= 255) continue; // already included in default set
|
if (c <= 255) continue; // already included in default set
|
||||||
sb.append(c);
|
sb.append(c);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ public abstract class LayeredScreen extends Screen {
|
|||||||
@Override
|
@Override
|
||||||
protected final void renderScreen()
|
protected final void renderScreen()
|
||||||
{
|
{
|
||||||
for (ScreenLayer layer : layers) {
|
for (final ScreenLayer layer : layers) {
|
||||||
layer.render();
|
layer.render();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import mightypork.rogue.bus.events.ScreenChangeEvent;
|
|||||||
import mightypork.rogue.input.KeyBinder;
|
import mightypork.rogue.input.KeyBinder;
|
||||||
import mightypork.rogue.input.KeyBindingPool;
|
import mightypork.rogue.input.KeyBindingPool;
|
||||||
import mightypork.rogue.input.KeyStroke;
|
import mightypork.rogue.input.KeyStroke;
|
||||||
|
import mightypork.rogue.render.Renderable;
|
||||||
import mightypork.utils.control.interf.Destroyable;
|
import mightypork.utils.control.interf.Destroyable;
|
||||||
import mightypork.utils.math.constraints.ConstraintContext;
|
import mightypork.utils.math.constraints.ConstraintContext;
|
||||||
import mightypork.utils.math.coord.Coord;
|
import mightypork.utils.math.coord.Coord;
|
||||||
@@ -19,7 +20,7 @@ import mightypork.utils.math.coord.Rect;
|
|||||||
*
|
*
|
||||||
* @author MightyPork
|
* @author MightyPork
|
||||||
*/
|
*/
|
||||||
public abstract class Screen extends ChildClient implements Destroyable, KeyBinder, ConstraintContext, ScreenChangeEvent.Listener {
|
public abstract class Screen extends ChildClient implements Renderable, Destroyable, KeyBinder, ConstraintContext, ScreenChangeEvent.Listener {
|
||||||
|
|
||||||
private final KeyBindingPool keybindings = new KeyBindingPool();
|
private final KeyBindingPool keybindings = new KeyBindingPool();
|
||||||
|
|
||||||
@@ -148,6 +149,7 @@ public abstract class Screen extends ChildClient implements Destroyable, KeyBind
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
public final void render()
|
public final void render()
|
||||||
{
|
{
|
||||||
if (!isActive()) return;
|
if (!isActive()) return;
|
||||||
@@ -165,7 +167,7 @@ public abstract class Screen extends ChildClient implements Destroyable, KeyBind
|
|||||||
// fix projection for changed size
|
// fix projection for changed size
|
||||||
glMatrixMode(GL_PROJECTION);
|
glMatrixMode(GL_PROJECTION);
|
||||||
glLoadIdentity();
|
glLoadIdentity();
|
||||||
Coord s = disp().getSize();
|
final Coord s = disp().getSize();
|
||||||
glViewport(0, 0, s.xi(), s.yi());
|
glViewport(0, 0, s.xi(), s.yi());
|
||||||
glOrtho(0, s.x, s.y, 0, -1000, 1000);
|
glOrtho(0, s.x, s.y, 0, -1000, 1000);
|
||||||
|
|
||||||
|
|||||||
@@ -2,10 +2,10 @@ package mightypork.rogue.gui;
|
|||||||
|
|
||||||
|
|
||||||
import mightypork.rogue.bus.ChildClient;
|
import mightypork.rogue.bus.ChildClient;
|
||||||
import mightypork.rogue.gui.constraints.Renderable;
|
|
||||||
import mightypork.rogue.input.KeyBinder;
|
import mightypork.rogue.input.KeyBinder;
|
||||||
import mightypork.rogue.input.KeyBindingPool;
|
import mightypork.rogue.input.KeyBindingPool;
|
||||||
import mightypork.rogue.input.KeyStroke;
|
import mightypork.rogue.input.KeyStroke;
|
||||||
|
import mightypork.rogue.render.Renderable;
|
||||||
import mightypork.utils.math.constraints.ConstraintContext;
|
import mightypork.utils.math.constraints.ConstraintContext;
|
||||||
import mightypork.utils.math.coord.Rect;
|
import mightypork.utils.math.coord.Rect;
|
||||||
|
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ public class ScreenRegistry extends Subsystem implements ScreenRequestEvent.List
|
|||||||
{
|
{
|
||||||
Log.f3("Request to show screen \"" + key + "\"");
|
Log.f3("Request to show screen \"" + key + "\"");
|
||||||
|
|
||||||
Screen toshow = screens.get(key);
|
final Screen toshow = screens.get(key);
|
||||||
if (toshow == null) throw new RuntimeException("Screen " + key + " not defined.");
|
if (toshow == null) throw new RuntimeException("Screen " + key + " not defined.");
|
||||||
|
|
||||||
if (active != null) active.setActive(false);
|
if (active != null) active.setActive(false);
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import java.util.LinkedList;
|
|||||||
|
|
||||||
import mightypork.rogue.AppAccess;
|
import mightypork.rogue.AppAccess;
|
||||||
import mightypork.rogue.bus.ChildClient;
|
import mightypork.rogue.bus.ChildClient;
|
||||||
|
import mightypork.rogue.render.Renderable;
|
||||||
import mightypork.utils.control.bus.EventBus;
|
import mightypork.utils.control.bus.EventBus;
|
||||||
import mightypork.utils.math.constraints.ConstraintContext;
|
import mightypork.utils.math.constraints.ConstraintContext;
|
||||||
import mightypork.utils.math.constraints.RectConstraint;
|
import mightypork.utils.math.constraints.RectConstraint;
|
||||||
@@ -44,7 +45,7 @@ public class ElementHolder extends ChildClient implements ConstraintContext, Ren
|
|||||||
@Override
|
@Override
|
||||||
public void render()
|
public void render()
|
||||||
{
|
{
|
||||||
for (Renderable element : elements) {
|
for (final Renderable element : elements) {
|
||||||
element.render();
|
element.render();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -57,19 +58,6 @@ public class ElementHolder extends ChildClient implements ConstraintContext, Ren
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// /**
|
|
||||||
// * Add element to the holder.
|
|
||||||
// *
|
|
||||||
// * @param elem
|
|
||||||
// */
|
|
||||||
// public void add(RenderableWithContext elem)
|
|
||||||
// {
|
|
||||||
// if (elem == null) return;
|
|
||||||
// elem.setContext(this);
|
|
||||||
// elements.add(elem);
|
|
||||||
// addChildClient(elem);
|
|
||||||
// }
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add element to the holder.
|
* Add element to the holder.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package mightypork.rogue.gui.constraints;
|
package mightypork.rogue.gui.constraints;
|
||||||
|
|
||||||
|
|
||||||
|
import mightypork.rogue.render.Renderable;
|
||||||
import mightypork.utils.math.constraints.ConstraintContext;
|
import mightypork.utils.math.constraints.ConstraintContext;
|
||||||
import mightypork.utils.math.constraints.SettableContext;
|
import mightypork.utils.math.constraints.SettableContext;
|
||||||
|
|
||||||
@@ -13,9 +14,5 @@ import mightypork.utils.math.constraints.SettableContext;
|
|||||||
public interface RenderableWithContext extends Renderable, SettableContext {
|
public interface RenderableWithContext extends Renderable, SettableContext {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void render();
|
void setContext(ConstraintContext context);
|
||||||
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setContext(ConstraintContext context);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,23 +19,23 @@ import mightypork.utils.math.coord.Rect;
|
|||||||
|
|
||||||
public class BouncyBox implements RenderableWithContext, Updateable, ConstraintContext {
|
public class BouncyBox implements RenderableWithContext, Updateable, ConstraintContext {
|
||||||
|
|
||||||
private Random rand = new Random();
|
private final Random rand = new Random();
|
||||||
|
|
||||||
private ConstraintContext context;
|
private ConstraintContext context;
|
||||||
|
|
||||||
private RectConstraint box;
|
private final RectConstraint box;
|
||||||
|
|
||||||
private AnimDouble pos = new AnimDouble(0, Easing.BOUNCE_OUT);
|
private final AnimDouble pos = new AnimDouble(0, Easing.BOUNCE_OUT);
|
||||||
|
|
||||||
|
|
||||||
public BouncyBox() {
|
public BouncyBox() {
|
||||||
// create box
|
// create box
|
||||||
NumConstraint side = c_height(this);
|
final NumConstraint side = c_height(this);
|
||||||
RectConstraint abox = c_box_sized(this, side, side);
|
RectConstraint abox = c_box_sized(this, side, side);
|
||||||
|
|
||||||
// move
|
// move
|
||||||
NumConstraint move_length = c_sub(c_width(this), side);
|
final NumConstraint move_length = c_sub(c_width(this), side);
|
||||||
NumConstraint offset = c_mul(move_length, c_n(pos));
|
final NumConstraint offset = c_mul(move_length, c_n(pos));
|
||||||
abox = c_move(abox, offset, c_n(0));
|
abox = c_move(abox, offset, c_n(0));
|
||||||
|
|
||||||
// add padding
|
// add padding
|
||||||
|
|||||||
@@ -22,12 +22,12 @@ public class LayerBouncyBoxes extends ScreenLayer {
|
|||||||
super(screen);
|
super(screen);
|
||||||
|
|
||||||
// shrink screen rect by 8% on all sides
|
// shrink screen rect by 8% on all sides
|
||||||
RectConstraint holder_rect = c_shrink(this, c_percent(c_height(this), c_n(8)));
|
final RectConstraint holder_rect = c_shrink(this, c_percent(c_height(this), c_n(8)));
|
||||||
|
|
||||||
addChildClient(layout = new RowHolder(screen, holder_rect, 16));
|
addChildClient(layout = new RowHolder(screen, holder_rect, 16));
|
||||||
|
|
||||||
for (int i = 0; i < 16; i++) {
|
for (int i = 0; i < 16; i++) {
|
||||||
BouncyBox bbr = new BouncyBox();
|
final BouncyBox bbr = new BouncyBox();
|
||||||
layout.addRow(bbr);
|
layout.addRow(bbr);
|
||||||
boxes.add(bbr);
|
boxes.add(bbr);
|
||||||
}
|
}
|
||||||
@@ -44,7 +44,7 @@ public class LayerBouncyBoxes extends ScreenLayer {
|
|||||||
|
|
||||||
public void goLeft()
|
public void goLeft()
|
||||||
{
|
{
|
||||||
for (BouncyBox bbr : boxes) {
|
for (final BouncyBox bbr : boxes) {
|
||||||
bbr.goLeft();
|
bbr.goLeft();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -52,7 +52,7 @@ public class LayerBouncyBoxes extends ScreenLayer {
|
|||||||
|
|
||||||
public void goRight()
|
public void goRight()
|
||||||
{
|
{
|
||||||
for (BouncyBox bbr : boxes) {
|
for (final BouncyBox bbr : boxes) {
|
||||||
bbr.goRight();
|
bbr.goRight();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import org.lwjgl.input.Keyboard;
|
|||||||
|
|
||||||
public class ScreenTestBouncy extends LayeredScreen {
|
public class ScreenTestBouncy extends LayeredScreen {
|
||||||
|
|
||||||
private LayerBouncyBoxes layer;
|
private final LayerBouncyBoxes layer;
|
||||||
|
|
||||||
|
|
||||||
public ScreenTestBouncy(AppAccess app) {
|
public ScreenTestBouncy(AppAccess app) {
|
||||||
|
|||||||
@@ -23,15 +23,15 @@ import org.newdawn.slick.opengl.Texture;
|
|||||||
|
|
||||||
public class LayerFlyingCat extends ScreenLayer implements Updateable, MouseButtonEvent.Listener {
|
public class LayerFlyingCat extends ScreenLayer implements Updateable, MouseButtonEvent.Listener {
|
||||||
|
|
||||||
private RectConstraint kittenbox;
|
private final RectConstraint kittenbox;
|
||||||
|
|
||||||
private AnimDouble s = new AnimDouble(400, Easing.SINE_BOTH);
|
private final AnimDouble s = new AnimDouble(400, Easing.SINE_BOTH);
|
||||||
private AnimDouble x = new AnimDouble(200, Easing.ELASTIC_OUT);
|
private final AnimDouble x = new AnimDouble(200, Easing.ELASTIC_OUT);
|
||||||
private AnimDouble y = new AnimDouble(200, Easing.ELASTIC_OUT);
|
private final AnimDouble y = new AnimDouble(200, Easing.ELASTIC_OUT);
|
||||||
|
|
||||||
private Random rand = new Random();
|
private final Random rand = new Random();
|
||||||
|
|
||||||
private Texture cat_tx = Res.getTexture("test.kitten");
|
private final Texture cat_tx = Res.getTexture("test.kitten");
|
||||||
|
|
||||||
|
|
||||||
public LayerFlyingCat(Screen screen) {
|
public LayerFlyingCat(Screen screen) {
|
||||||
@@ -65,11 +65,11 @@ public class LayerFlyingCat extends ScreenLayer implements Updateable, MouseButt
|
|||||||
{
|
{
|
||||||
if (!event.isDown()) return;
|
if (!event.isDown()) return;
|
||||||
|
|
||||||
Coord pos = event.getPos();
|
final Coord pos = event.getPos();
|
||||||
|
|
||||||
double newSize = 200 + rand.nextInt(600);
|
final double newSize = 200 + rand.nextInt(600);
|
||||||
|
|
||||||
double t = 2;
|
final double t = 2;
|
||||||
|
|
||||||
s.fadeTo(newSize, t / 2D);
|
s.fadeTo(newSize, t / 2D);
|
||||||
x.fadeTo(pos.x - newSize / 2D, t);
|
x.fadeTo(pos.x - newSize / 2D, t);
|
||||||
|
|||||||
@@ -40,10 +40,10 @@ public class ScreenTestFont extends Screen {
|
|||||||
@Override
|
@Override
|
||||||
protected void renderScreen()
|
protected void renderScreen()
|
||||||
{
|
{
|
||||||
GLFont font = Res.getFont("PolygonPixel_16");
|
final GLFont font = Res.getFont("PolygonPixel_16");
|
||||||
|
|
||||||
String s = "It works!";
|
final String s = "It works!";
|
||||||
double scale = getRect().height() / 50D;
|
final double scale = getRect().height() / 50D;
|
||||||
Render.pushState();
|
Render.pushState();
|
||||||
Render.translate(getRect().getCenter().sub(font.getNeededSpace(s).mul(scale).half()));
|
Render.translate(getRect().getCenter().sub(font.getNeededSpace(s).mul(scale).half()));
|
||||||
Render.scale(new Coord(scale));
|
Render.scale(new Coord(scale));
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ public class InputSystem extends Subsystem implements Updateable, KeyBinder {
|
|||||||
Mouse.create();
|
Mouse.create();
|
||||||
Keyboard.create();
|
Keyboard.create();
|
||||||
Keyboard.enableRepeatEvents(false);
|
Keyboard.enableRepeatEvents(false);
|
||||||
} catch (LWJGLException e) {
|
} catch (final LWJGLException e) {
|
||||||
throw new RuntimeException("Failed to initialize input devices.", e);
|
throw new RuntimeException("Failed to initialize input devices.", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -83,8 +83,8 @@ public class InputSystem extends Subsystem implements Updateable, KeyBinder {
|
|||||||
|
|
||||||
Display.processMessages();
|
Display.processMessages();
|
||||||
|
|
||||||
Coord moveSum = Coord.zero();
|
final Coord moveSum = Coord.zero();
|
||||||
Coord lastPos = Coord.zero();
|
final Coord lastPos = Coord.zero();
|
||||||
boolean wasMouse = false;
|
boolean wasMouse = false;
|
||||||
|
|
||||||
while (Mouse.next()) {
|
while (Mouse.next()) {
|
||||||
@@ -106,11 +106,11 @@ public class InputSystem extends Subsystem implements Updateable, KeyBinder {
|
|||||||
|
|
||||||
private void onMouseEvent(Coord moveSum, Coord lastPos)
|
private void onMouseEvent(Coord moveSum, Coord lastPos)
|
||||||
{
|
{
|
||||||
int button = Mouse.getEventButton();
|
final int button = Mouse.getEventButton();
|
||||||
boolean down = Mouse.getEventButtonState();
|
final boolean down = Mouse.getEventButtonState();
|
||||||
Coord pos = new Coord(Mouse.getEventX(), Mouse.getEventY());
|
final Coord pos = new Coord(Mouse.getEventX(), Mouse.getEventY());
|
||||||
Coord move = new Coord(Mouse.getEventDX(), Mouse.getEventDY());
|
final Coord move = new Coord(Mouse.getEventDX(), Mouse.getEventDY());
|
||||||
int wheeld = Mouse.getEventDWheel();
|
final int wheeld = Mouse.getEventDWheel();
|
||||||
|
|
||||||
if (yAxisDown) {
|
if (yAxisDown) {
|
||||||
flipScrY(pos);
|
flipScrY(pos);
|
||||||
@@ -128,9 +128,9 @@ public class InputSystem extends Subsystem implements Updateable, KeyBinder {
|
|||||||
|
|
||||||
private void onKeyEvent()
|
private void onKeyEvent()
|
||||||
{
|
{
|
||||||
int key = Keyboard.getEventKey();
|
final int key = Keyboard.getEventKey();
|
||||||
boolean down = Keyboard.getEventKeyState();
|
final boolean down = Keyboard.getEventKeyState();
|
||||||
char c = Keyboard.getEventCharacter();
|
final char c = Keyboard.getEventCharacter();
|
||||||
|
|
||||||
bus().queue(new KeyboardEvent(key, c, down));
|
bus().queue(new KeyboardEvent(key, c, down));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ public interface KeyBinder {
|
|||||||
* @param stroke trigger keystroke
|
* @param stroke trigger keystroke
|
||||||
* @param task handler
|
* @param task handler
|
||||||
*/
|
*/
|
||||||
abstract void bindKeyStroke(KeyStroke stroke, Runnable task);
|
void bindKeyStroke(KeyStroke stroke, Runnable task);
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -17,6 +17,6 @@ public interface KeyBinder {
|
|||||||
*
|
*
|
||||||
* @param stroke stroke
|
* @param stroke stroke
|
||||||
*/
|
*/
|
||||||
abstract void unbindKeyStroke(KeyStroke stroke);
|
void unbindKeyStroke(KeyStroke stroke);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,11 @@ package mightypork.rogue.input;
|
|||||||
import mightypork.rogue.bus.events.KeyboardEvent;
|
import mightypork.rogue.bus.events.KeyboardEvent;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Key binding, trigger activated by a keystroke event
|
||||||
|
*
|
||||||
|
* @author MightyPork
|
||||||
|
*/
|
||||||
public class KeyBinding implements KeyboardEvent.Listener {
|
public class KeyBinding implements KeyboardEvent.Listener {
|
||||||
|
|
||||||
private final KeyStroke keystroke;
|
private final KeyStroke keystroke;
|
||||||
@@ -11,6 +16,10 @@ public class KeyBinding implements KeyboardEvent.Listener {
|
|||||||
private boolean wasActive = false;
|
private boolean wasActive = false;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param stroke trigger keystroke
|
||||||
|
* @param handler action
|
||||||
|
*/
|
||||||
public KeyBinding(KeyStroke stroke, Runnable handler) {
|
public KeyBinding(KeyStroke stroke, Runnable handler) {
|
||||||
this.keystroke = stroke;
|
this.keystroke = stroke;
|
||||||
this.handler = handler;
|
this.handler = handler;
|
||||||
@@ -19,12 +28,21 @@ public class KeyBinding implements KeyboardEvent.Listener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check for equality of keystroke
|
||||||
|
*
|
||||||
|
* @param stroke other keystroke
|
||||||
|
* @return true if keystrokes are equal (cannot co-exist)
|
||||||
|
*/
|
||||||
public boolean matches(KeyStroke stroke)
|
public boolean matches(KeyStroke stroke)
|
||||||
{
|
{
|
||||||
return this.keystroke.equals(stroke);
|
return this.keystroke.equals(stroke);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param handler event handler
|
||||||
|
*/
|
||||||
public void setHandler(Runnable handler)
|
public void setHandler(Runnable handler)
|
||||||
{
|
{
|
||||||
this.handler = handler;
|
this.handler = handler;
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ public class KeyBindingPool implements KeyBinder, KeyboardEvent.Listener {
|
|||||||
@Override
|
@Override
|
||||||
public void bindKeyStroke(KeyStroke stroke, Runnable task)
|
public void bindKeyStroke(KeyStroke stroke, Runnable task)
|
||||||
{
|
{
|
||||||
for (KeyBinding kb : bindings) {
|
for (final KeyBinding kb : bindings) {
|
||||||
if (kb.matches(stroke)) {
|
if (kb.matches(stroke)) {
|
||||||
Log.w("Duplicate KeyBinding (" + stroke + "), using newest handler.");
|
Log.w("Duplicate KeyBinding (" + stroke + "), using newest handler.");
|
||||||
kb.setHandler(task);
|
kb.setHandler(task);
|
||||||
@@ -48,10 +48,10 @@ public class KeyBindingPool implements KeyBinder, KeyboardEvent.Listener {
|
|||||||
@Override
|
@Override
|
||||||
public void unbindKeyStroke(KeyStroke stroke)
|
public void unbindKeyStroke(KeyStroke stroke)
|
||||||
{
|
{
|
||||||
Iterator<KeyBinding> iter = bindings.iterator();
|
final Iterator<KeyBinding> iter = bindings.iterator();
|
||||||
|
|
||||||
while (iter.hasNext()) {
|
while (iter.hasNext()) {
|
||||||
KeyBinding kb = iter.next();
|
final KeyBinding kb = iter.next();
|
||||||
if (kb.matches(stroke)) {
|
if (kb.matches(stroke)) {
|
||||||
iter.remove();
|
iter.remove();
|
||||||
return;
|
return;
|
||||||
@@ -63,7 +63,7 @@ public class KeyBindingPool implements KeyBinder, KeyboardEvent.Listener {
|
|||||||
@Override
|
@Override
|
||||||
public void receive(KeyboardEvent event)
|
public void receive(KeyboardEvent event)
|
||||||
{
|
{
|
||||||
for (KeyBinding kb : bindings) {
|
for (final KeyBinding kb : bindings) {
|
||||||
kb.receive(event);
|
kb.receive(event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,11 @@ import java.util.Set;
|
|||||||
import org.lwjgl.input.Keyboard;
|
import org.lwjgl.input.Keyboard;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Key stroke trigger
|
||||||
|
*
|
||||||
|
* @author MightyPork
|
||||||
|
*/
|
||||||
public class KeyStroke {
|
public class KeyStroke {
|
||||||
|
|
||||||
private final Set<Integer> keys = new LinkedHashSet<Integer>();
|
private final Set<Integer> keys = new LinkedHashSet<Integer>();
|
||||||
@@ -22,7 +27,7 @@ public class KeyStroke {
|
|||||||
*/
|
*/
|
||||||
public KeyStroke(boolean fallingEdge, int... keys) {
|
public KeyStroke(boolean fallingEdge, int... keys) {
|
||||||
this.fallingEdge = fallingEdge;
|
this.fallingEdge = fallingEdge;
|
||||||
for (int k : keys) {
|
for (final int k : keys) {
|
||||||
this.keys.add(k);
|
this.keys.add(k);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -35,16 +40,19 @@ public class KeyStroke {
|
|||||||
*/
|
*/
|
||||||
public KeyStroke(int... keys) {
|
public KeyStroke(int... keys) {
|
||||||
fallingEdge = false;
|
fallingEdge = false;
|
||||||
for (int k : keys) {
|
for (final int k : keys) {
|
||||||
this.keys.add(k);
|
this.keys.add(k);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return true if the keystroke is currently satisfied (keys pressed)
|
||||||
|
*/
|
||||||
public boolean isActive()
|
public boolean isActive()
|
||||||
{
|
{
|
||||||
boolean st = true;
|
boolean st = true;
|
||||||
for (int k : keys) {
|
for (final int k : keys) {
|
||||||
st &= Keyboard.isKeyDown(k);
|
st &= Keyboard.isKeyDown(k);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,7 +76,7 @@ public class KeyStroke {
|
|||||||
if (this == obj) return true;
|
if (this == obj) return true;
|
||||||
if (obj == null) return false;
|
if (obj == null) return false;
|
||||||
if (!(obj instanceof KeyStroke)) return false;
|
if (!(obj instanceof KeyStroke)) return false;
|
||||||
KeyStroke other = (KeyStroke) obj;
|
final KeyStroke other = (KeyStroke) obj;
|
||||||
|
|
||||||
if (keys == null) {
|
if (keys == null) {
|
||||||
if (other.keys != null) return false;
|
if (other.keys != null) return false;
|
||||||
@@ -88,7 +96,7 @@ public class KeyStroke {
|
|||||||
String s = "(";
|
String s = "(";
|
||||||
|
|
||||||
int cnt = 0;
|
int cnt = 0;
|
||||||
Iterator<Integer> i = keys.iterator();
|
final Iterator<Integer> i = keys.iterator();
|
||||||
for (; i.hasNext(); cnt++) {
|
for (; i.hasNext(); cnt++) {
|
||||||
if (cnt > 0) s += "+";
|
if (cnt > 0) s += "+";
|
||||||
s += Keyboard.getKeyName(i.next());
|
s += Keyboard.getKeyName(i.next());
|
||||||
@@ -102,6 +110,9 @@ public class KeyStroke {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return the key set
|
||||||
|
*/
|
||||||
public Set<Integer> getKeys()
|
public Set<Integer> getKeys()
|
||||||
{
|
{
|
||||||
return keys;
|
return keys;
|
||||||
|
|||||||
+14
-16
@@ -17,28 +17,29 @@ import mightypork.utils.logging.Log;
|
|||||||
*
|
*
|
||||||
* @author MightyPork
|
* @author MightyPork
|
||||||
*/
|
*/
|
||||||
public class DeferredLoader extends Thread implements ResourceLoadRequest.Listener, Destroyable {
|
public class AsyncResourceLoader extends Thread implements ResourceLoadRequest.Listener, Destroyable {
|
||||||
|
|
||||||
public static void launch(AppAccess app)
|
public static void launch(AppAccess app)
|
||||||
{
|
{
|
||||||
(new DeferredLoader(app)).start();
|
(new AsyncResourceLoader(app)).start();
|
||||||
}
|
}
|
||||||
|
|
||||||
private ExecutorService exs = Executors.newCachedThreadPool();
|
private final ExecutorService exs = Executors.newCachedThreadPool();
|
||||||
|
|
||||||
private LinkedBlockingQueue<Deferred> toLoad = new LinkedBlockingQueue<Deferred>();
|
private final LinkedBlockingQueue<DeferredResource> toLoad = new LinkedBlockingQueue<DeferredResource>();
|
||||||
private boolean stopped;
|
private boolean stopped;
|
||||||
private AppAccess app;
|
private final AppAccess app;
|
||||||
|
|
||||||
|
|
||||||
public DeferredLoader(AppAccess app) {
|
public AsyncResourceLoader(AppAccess app) {
|
||||||
super("Deferred loader");
|
super("Deferred loader");
|
||||||
this.app = app;
|
this.app = app;
|
||||||
|
app.bus().subscribe(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void loadResource(Deferred resource)
|
public void loadResource(DeferredResource resource)
|
||||||
{
|
{
|
||||||
toLoad.add(resource);
|
toLoad.add(resource);
|
||||||
}
|
}
|
||||||
@@ -47,10 +48,12 @@ public class DeferredLoader extends Thread implements ResourceLoadRequest.Listen
|
|||||||
@Override
|
@Override
|
||||||
public void run()
|
public void run()
|
||||||
{
|
{
|
||||||
|
Log.f3("Asynchronous resource loader started.");
|
||||||
|
|
||||||
while (!stopped) {
|
while (!stopped) {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
final Deferred def = toLoad.take();
|
final DeferredResource def = toLoad.take();
|
||||||
if (def == null) continue;
|
if (def == null) continue;
|
||||||
|
|
||||||
if (!def.isLoaded()) {
|
if (!def.isLoaded()) {
|
||||||
@@ -58,11 +61,8 @@ public class DeferredLoader extends Thread implements ResourceLoadRequest.Listen
|
|||||||
// skip nulls
|
// skip nulls
|
||||||
if (def instanceof NullResource) continue;
|
if (def instanceof NullResource) continue;
|
||||||
|
|
||||||
// texture needs to be loaded in main thread, unfortunately.
|
// textures & fonts needs to be loaded in main thread
|
||||||
// -> delegate to MainLoop
|
if (def.getClass().isAnnotationPresent(MustLoadInMainThread.class)) {
|
||||||
if (def instanceof MustLoadInMainThread) {
|
|
||||||
Log.f3("<DEFERRED> Loading \"" + Log.str(def) + "\" in main thread (texture based).");
|
|
||||||
|
|
||||||
app.bus().queue(new MainLoopTaskRequest(new Runnable() {
|
app.bus().queue(new MainLoopTaskRequest(new Runnable() {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -75,8 +75,6 @@ public class DeferredLoader extends Thread implements ResourceLoadRequest.Listen
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
Log.f3("<DEFERRED> Loading \"" + Log.str(def) + "\" asynchronously.");
|
|
||||||
|
|
||||||
exs.submit(new Runnable() {
|
exs.submit(new Runnable() {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -87,7 +85,7 @@ public class DeferredLoader extends Thread implements ResourceLoadRequest.Listen
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (InterruptedException ignored) {
|
} catch (final InterruptedException ignored) {
|
||||||
//
|
//
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
package mightypork.rogue.loading;
|
||||||
|
|
||||||
|
|
||||||
|
import mightypork.utils.control.interf.Destroyable;
|
||||||
|
import mightypork.utils.logging.Log;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deferred resource abstraction.<br>
|
||||||
|
* Resources implementing {@link NullResource} will be treated as fake and not
|
||||||
|
* attempted to load.
|
||||||
|
*
|
||||||
|
* @author MightyPork
|
||||||
|
*/
|
||||||
|
public abstract class BaseDeferredResource implements DeferredResource, Destroyable {
|
||||||
|
|
||||||
|
private final String resource;
|
||||||
|
private boolean loadFailed = false;
|
||||||
|
private boolean loadAttempted = false;
|
||||||
|
|
||||||
|
|
||||||
|
public BaseDeferredResource(String resource) {
|
||||||
|
this.resource = resource;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public synchronized final void load()
|
||||||
|
{
|
||||||
|
|
||||||
|
if (loadAttempted) return;
|
||||||
|
|
||||||
|
loadAttempted = true;
|
||||||
|
loadFailed = false;
|
||||||
|
|
||||||
|
if (isNull()) return;
|
||||||
|
try {
|
||||||
|
if (resource == null) throw new NullPointerException("Resource string cannot be null for non-null resource.");
|
||||||
|
|
||||||
|
Log.f3("<res> Loading: " + this);
|
||||||
|
loadResource(resource);
|
||||||
|
Log.f3("<res> Loaded: " + this + " loaded.");
|
||||||
|
} catch (final Exception e) {
|
||||||
|
loadFailed = true;
|
||||||
|
Log.e("Failed to load resource \"" + resource + "\"", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public synchronized final boolean isLoaded()
|
||||||
|
{
|
||||||
|
if (isNull()) return false;
|
||||||
|
|
||||||
|
return loadAttempted && !loadFailed;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the resource is loaded; if not, try to do so.
|
||||||
|
*
|
||||||
|
* @return true if it's loaded now.
|
||||||
|
*/
|
||||||
|
public synchronized final boolean ensureLoaded()
|
||||||
|
{
|
||||||
|
if (isNull()) return false;
|
||||||
|
|
||||||
|
if (isLoaded()) {
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
load();
|
||||||
|
}
|
||||||
|
|
||||||
|
return isLoaded();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load the resource. Called from load() - once only.
|
||||||
|
*
|
||||||
|
* @param resource the path / name of a resource
|
||||||
|
* @throws Exception when some problem prevented the resource from being
|
||||||
|
* loaded.
|
||||||
|
*/
|
||||||
|
protected abstract void loadResource(String resource) throws Exception;
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public abstract void destroy();
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString()
|
||||||
|
{
|
||||||
|
return Log.str(getClass()) + "(\"" + resource + "\")";
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode()
|
||||||
|
{
|
||||||
|
final int prime = 31;
|
||||||
|
int result = 1;
|
||||||
|
result = prime * result + ((resource == null) ? 0 : resource.hashCode());
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj)
|
||||||
|
{
|
||||||
|
if (this == obj) return true;
|
||||||
|
if (obj == null) return false;
|
||||||
|
if (!(obj instanceof BaseDeferredResource)) return false;
|
||||||
|
final BaseDeferredResource other = (BaseDeferredResource) obj;
|
||||||
|
if (resource == null) {
|
||||||
|
if (other.resource != null) return false;
|
||||||
|
} else if (!resource.equals(other.resource)) return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private boolean isNull()
|
||||||
|
{
|
||||||
|
return this instanceof NullResource;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
package mightypork.rogue.loading;
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Deferred resource
|
|
||||||
*
|
|
||||||
* @author MightyPork
|
|
||||||
*/
|
|
||||||
public interface Deferred {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Load the actual resource, if not loaded yet.
|
|
||||||
*/
|
|
||||||
public void load();
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if resource was successfully loaded.
|
|
||||||
*
|
|
||||||
* @return true if already loaded
|
|
||||||
*/
|
|
||||||
public boolean isLoaded();
|
|
||||||
}
|
|
||||||
@@ -1,127 +1,23 @@
|
|||||||
package mightypork.rogue.loading;
|
package mightypork.rogue.loading;
|
||||||
|
|
||||||
|
|
||||||
import mightypork.utils.control.interf.Destroyable;
|
|
||||||
import mightypork.utils.logging.Log;
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Deferred resource abstraction.<br>
|
* Deferred resource
|
||||||
* Resources implementing {@link NullResource} will be treated as fake and not
|
|
||||||
* attempted to load.
|
|
||||||
*
|
*
|
||||||
* @author MightyPork
|
* @author MightyPork
|
||||||
*/
|
*/
|
||||||
public abstract class DeferredResource implements Deferred, Destroyable {
|
public interface DeferredResource {
|
||||||
|
|
||||||
private String resource;
|
/**
|
||||||
private boolean loadFailed = false;
|
* Load the actual resource, if not loaded yet.
|
||||||
private boolean loadAttempted = false;
|
*/
|
||||||
|
void load();
|
||||||
|
|
||||||
public DeferredResource(String resource) {
|
|
||||||
this.resource = resource;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public synchronized final void load()
|
|
||||||
{
|
|
||||||
|
|
||||||
if (loadAttempted) return;
|
|
||||||
|
|
||||||
loadAttempted = true;
|
|
||||||
loadFailed = false;
|
|
||||||
|
|
||||||
if (isNull()) return;
|
|
||||||
try {
|
|
||||||
if (resource == null) throw new NullPointerException("Resource string cannot be null for non-null resource.");
|
|
||||||
|
|
||||||
Log.f3("Loading resource " + this);
|
|
||||||
loadResource(resource);
|
|
||||||
Log.f3("Resource " + this + " loaded.");
|
|
||||||
} catch (Exception e) {
|
|
||||||
loadFailed = true;
|
|
||||||
Log.e("Failed to load resource \"" + resource + "\"", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public synchronized final boolean isLoaded()
|
|
||||||
{
|
|
||||||
if (isNull()) return false;
|
|
||||||
|
|
||||||
return loadAttempted && !loadFailed;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if the resource is loaded; if not, try to do so.
|
* Check if resource was successfully loaded.
|
||||||
*
|
*
|
||||||
* @return true if it's loaded now.
|
* @return true if already loaded
|
||||||
*/
|
*/
|
||||||
public synchronized final boolean ensureLoaded()
|
boolean isLoaded();
|
||||||
{
|
|
||||||
if (isNull()) return false;
|
|
||||||
|
|
||||||
if (isLoaded()) {
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
load();
|
|
||||||
}
|
|
||||||
|
|
||||||
return isLoaded();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Load the resource. Called from load() - once only.
|
|
||||||
*
|
|
||||||
* @param resource the path / name of a resource
|
|
||||||
* @throws Exception when some problem prevented the resource from being
|
|
||||||
* loaded.
|
|
||||||
*/
|
|
||||||
protected abstract void loadResource(String resource) throws Exception;
|
|
||||||
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public abstract void destroy();
|
|
||||||
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString()
|
|
||||||
{
|
|
||||||
return Log.str(getClass()) + "(\"" + resource + "\")";
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int hashCode()
|
|
||||||
{
|
|
||||||
final int prime = 31;
|
|
||||||
int result = 1;
|
|
||||||
result = prime * result + ((resource == null) ? 0 : resource.hashCode());
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean equals(Object obj)
|
|
||||||
{
|
|
||||||
if (this == obj) return true;
|
|
||||||
if (obj == null) return false;
|
|
||||||
if (!(obj instanceof DeferredResource)) return false;
|
|
||||||
DeferredResource other = (DeferredResource) obj;
|
|
||||||
if (resource == null) {
|
|
||||||
if (other.resource != null) return false;
|
|
||||||
} else if (!resource.equals(other.resource)) return false;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private boolean isNull()
|
|
||||||
{
|
|
||||||
return this instanceof NullResource;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,18 @@
|
|||||||
package mightypork.rogue.loading;
|
package mightypork.rogue.loading;
|
||||||
|
|
||||||
|
|
||||||
|
import java.lang.annotation.*;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resource that is texture-based and therefore needs to be loaded in the main
|
* Resource that is texture-based and therefore needs to be loaded in the main
|
||||||
* thread (ie. main loop).
|
* thread (ie. main loop).
|
||||||
*
|
*
|
||||||
* @author MightyPork
|
* @author MightyPork
|
||||||
*/
|
*/
|
||||||
public interface MustLoadInMainThread {
|
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
}
|
@Target(ElementType.TYPE)
|
||||||
|
@Inherited
|
||||||
|
@Documented
|
||||||
|
public @interface MustLoadInMainThread {}
|
||||||
|
|||||||
@@ -59,7 +59,7 @@ public class DisplaySystem extends Subsystem implements ConstraintContext {
|
|||||||
|
|
||||||
Render.init();
|
Render.init();
|
||||||
|
|
||||||
} catch (LWJGLException e) {
|
} catch (final LWJGLException e) {
|
||||||
throw new RuntimeException("Could not initialize screen", e);
|
throw new RuntimeException("Could not initialize screen", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -88,12 +88,12 @@ public class DisplaySystem extends Subsystem implements ConstraintContext {
|
|||||||
|
|
||||||
bus().queue(new ScreenChangeEvent(true, Display.isFullscreen(), getSize()));
|
bus().queue(new ScreenChangeEvent(true, Display.isFullscreen(), getSize()));
|
||||||
|
|
||||||
} catch (Throwable t) {
|
} catch (final Throwable t) {
|
||||||
Log.e("Failed to toggle fullscreen mode.", t);
|
Log.e("Failed to toggle fullscreen mode.", t);
|
||||||
try {
|
try {
|
||||||
Display.setDisplayMode(windowDisplayMode);
|
Display.setDisplayMode(windowDisplayMode);
|
||||||
Display.update();
|
Display.update();
|
||||||
} catch (Throwable t1) {
|
} catch (final Throwable t1) {
|
||||||
throw new RuntimeException("Failed to revert failed fullscreen toggle.", t1);
|
throw new RuntimeException("Failed to revert failed fullscreen toggle.", t1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -103,14 +103,14 @@ public class DisplaySystem extends Subsystem implements ConstraintContext {
|
|||||||
public Screenshot takeScreenshot()
|
public Screenshot takeScreenshot()
|
||||||
{
|
{
|
||||||
glReadBuffer(GL_FRONT);
|
glReadBuffer(GL_FRONT);
|
||||||
int width = Display.getDisplayMode().getWidth();
|
final int width = Display.getDisplayMode().getWidth();
|
||||||
int height = Display.getDisplayMode().getHeight();
|
final int height = Display.getDisplayMode().getHeight();
|
||||||
int bpp = 4; // Assuming a 32-bit display with a byte each for red,
|
final int bpp = 4; // Assuming a 32-bit display with a byte each for red,
|
||||||
// green, blue, and alpha.
|
// green, blue, and alpha.
|
||||||
ByteBuffer buffer = BufferUtils.createByteBuffer(width * height * bpp);
|
final ByteBuffer buffer = BufferUtils.createByteBuffer(width * height * bpp);
|
||||||
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
|
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
|
||||||
|
|
||||||
Screenshot sc = new Screenshot(width, height, bpp, buffer);
|
final Screenshot sc = new Screenshot(width, height, bpp, buffer);
|
||||||
|
|
||||||
return sc;
|
return sc;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import static org.lwjgl.opengl.GL11.*;
|
|||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
import mightypork.rogue.texture.TxQuad;
|
import mightypork.rogue.textures.TxQuad;
|
||||||
import mightypork.utils.files.FileUtils;
|
import mightypork.utils.files.FileUtils;
|
||||||
import mightypork.utils.logging.Log;
|
import mightypork.utils.logging.Log;
|
||||||
import mightypork.utils.math.color.RGB;
|
import mightypork.utils.math.color.RGB;
|
||||||
@@ -170,7 +170,7 @@ public class Render {
|
|||||||
*/
|
*/
|
||||||
public static void rotate(double angle, Coord axis)
|
public static void rotate(double angle, Coord axis)
|
||||||
{
|
{
|
||||||
Coord vec = axis.norm(1);
|
final Coord vec = axis.norm(1);
|
||||||
glRotated(angle, vec.x, vec.y, vec.z);
|
glRotated(angle, vec.x, vec.y, vec.z);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -204,11 +204,9 @@ public class Render {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
||||||
String ext = FileUtils.getExtension(resourcePath).toUpperCase();
|
final String ext = FileUtils.getExtension(resourcePath).toUpperCase();
|
||||||
|
|
||||||
Log.f3("Loading texture " + ext + " at " + resourcePath);
|
final Texture texture = TextureLoader.getTexture(ext, ResourceLoader.getResourceAsStream(resourcePath));
|
||||||
|
|
||||||
Texture texture = TextureLoader.getTexture(ext, ResourceLoader.getResourceAsStream(resourcePath));
|
|
||||||
|
|
||||||
if (texture == null) {
|
if (texture == null) {
|
||||||
Log.w("Texture " + resourcePath + " could not be loaded.");
|
Log.w("Texture " + resourcePath + " could not be loaded.");
|
||||||
@@ -216,7 +214,7 @@ public class Render {
|
|||||||
|
|
||||||
return texture;
|
return texture;
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
Log.e("Loading of texture " + resourcePath + " failed.", e);
|
Log.e("Loading of texture " + resourcePath + " failed.", e);
|
||||||
throw new RuntimeException("Could not load texture " + resourcePath + ".", e);
|
throw new RuntimeException("Could not load texture " + resourcePath + ".", e);
|
||||||
}
|
}
|
||||||
@@ -280,10 +278,10 @@ public class Render {
|
|||||||
*/
|
*/
|
||||||
public static void quad(Rect quad)
|
public static void quad(Rect quad)
|
||||||
{
|
{
|
||||||
double left = quad.xMin();
|
final double left = quad.xMin();
|
||||||
double bottom = quad.yMin();
|
final double bottom = quad.yMin();
|
||||||
double right = quad.xMax();
|
final double right = quad.xMax();
|
||||||
double top = quad.yMax();
|
final double top = quad.yMax();
|
||||||
|
|
||||||
// draw with color
|
// draw with color
|
||||||
unbindTexture();
|
unbindTexture();
|
||||||
@@ -320,15 +318,15 @@ public class Render {
|
|||||||
*/
|
*/
|
||||||
public static void quadUV_nobound(Rect quad, Rect uvs)
|
public static void quadUV_nobound(Rect quad, Rect uvs)
|
||||||
{
|
{
|
||||||
double left = quad.xMin();
|
final double left = quad.xMin();
|
||||||
double bottom = quad.yMin();
|
final double bottom = quad.yMin();
|
||||||
double right = quad.xMax();
|
final double right = quad.xMax();
|
||||||
double top = quad.yMax();
|
final double top = quad.yMax();
|
||||||
|
|
||||||
double tleft = uvs.xMin();
|
final double tleft = uvs.xMin();
|
||||||
double tbottom = uvs.yMin();
|
final double tbottom = uvs.yMin();
|
||||||
double tright = uvs.xMax();
|
final double tright = uvs.xMax();
|
||||||
double ttop = uvs.yMax();
|
final double ttop = uvs.yMax();
|
||||||
|
|
||||||
// quad with texture
|
// quad with texture
|
||||||
glTexCoord2d(tleft, ttop);
|
glTexCoord2d(tleft, ttop);
|
||||||
@@ -344,10 +342,10 @@ public class Render {
|
|||||||
|
|
||||||
public static void quadGradH(Rect quad, RGB colorLeft, RGB colorRight)
|
public static void quadGradH(Rect quad, RGB colorLeft, RGB colorRight)
|
||||||
{
|
{
|
||||||
double left = quad.xMin();
|
final double left = quad.xMin();
|
||||||
double bottom = quad.yMin();
|
final double bottom = quad.yMin();
|
||||||
double right = quad.yMax();
|
final double right = quad.yMax();
|
||||||
double top = quad.yMax();
|
final double top = quad.yMax();
|
||||||
|
|
||||||
// draw with color
|
// draw with color
|
||||||
unbindTexture();
|
unbindTexture();
|
||||||
@@ -368,10 +366,10 @@ public class Render {
|
|||||||
|
|
||||||
public static void quadGradV(Rect quad, RGB colorTop, RGB colorBottom)
|
public static void quadGradV(Rect quad, RGB colorTop, RGB colorBottom)
|
||||||
{
|
{
|
||||||
double left = quad.xMin();
|
final double left = quad.xMin();
|
||||||
double bottom = quad.yMin();
|
final double bottom = quad.yMin();
|
||||||
double right = quad.yMax();
|
final double right = quad.yMax();
|
||||||
double top = quad.yMax();
|
final double top = quad.yMax();
|
||||||
|
|
||||||
// draw with color
|
// draw with color
|
||||||
unbindTexture();
|
unbindTexture();
|
||||||
|
|||||||
+2
-2
@@ -1,4 +1,4 @@
|
|||||||
package mightypork.rogue.gui.constraints;
|
package mightypork.rogue.render;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -11,6 +11,6 @@ public interface Renderable {
|
|||||||
/**
|
/**
|
||||||
* Render on screen
|
* Render on screen
|
||||||
*/
|
*/
|
||||||
public void render();
|
void render();
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -3,7 +3,7 @@ package mightypork.rogue.sound;
|
|||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
import mightypork.rogue.loading.DeferredResource;
|
import mightypork.rogue.loading.BaseDeferredResource;
|
||||||
import mightypork.utils.files.FileUtils;
|
import mightypork.utils.files.FileUtils;
|
||||||
import mightypork.utils.math.coord.Coord;
|
import mightypork.utils.math.coord.Coord;
|
||||||
|
|
||||||
@@ -16,7 +16,7 @@ import org.newdawn.slick.openal.SoundStore;
|
|||||||
*
|
*
|
||||||
* @author MightyPork
|
* @author MightyPork
|
||||||
*/
|
*/
|
||||||
public class DeferredAudio extends DeferredResource {
|
public class DeferredAudio extends BaseDeferredResource {
|
||||||
|
|
||||||
private enum PlayMode
|
private enum PlayMode
|
||||||
{
|
{
|
||||||
@@ -86,7 +86,7 @@ public class DeferredAudio extends DeferredResource {
|
|||||||
@Override
|
@Override
|
||||||
protected void loadResource(String resource) throws IOException
|
protected void loadResource(String resource) throws IOException
|
||||||
{
|
{
|
||||||
String ext = FileUtils.getExtension(resource);
|
final String ext = FileUtils.getExtension(resource);
|
||||||
|
|
||||||
if (ext.equalsIgnoreCase("ogg")) {
|
if (ext.equalsIgnoreCase("ogg")) {
|
||||||
backingAudio = SoundStore.get().getOgg(resource);
|
backingAudio = SoundStore.get().getOgg(resource);
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ public class JointVolume extends Mutable<Double> {
|
|||||||
public Double get()
|
public Double get()
|
||||||
{
|
{
|
||||||
double d = super.get();
|
double d = super.get();
|
||||||
for (Mutable<Double> v : volumes)
|
for (final Mutable<Double> v : volumes)
|
||||||
d *= v.get();
|
d *= v.get();
|
||||||
|
|
||||||
return Calc.clampd(d, 0, 1);
|
return Calc.clampd(d, 0, 1);
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ public class SoundBank extends AppAdapter {
|
|||||||
*/
|
*/
|
||||||
public LoopPlayer getLoop(String key)
|
public LoopPlayer getLoop(String key)
|
||||||
{
|
{
|
||||||
LoopPlayer p = loops.get(key);
|
final LoopPlayer p = loops.get(key);
|
||||||
if (p == null) {
|
if (p == null) {
|
||||||
Log.w("Requesting unknown sound loop \"" + key + "\".");
|
Log.w("Requesting unknown sound loop \"" + key + "\".");
|
||||||
return NULL_LOOP;
|
return NULL_LOOP;
|
||||||
@@ -82,7 +82,7 @@ public class SoundBank extends AppAdapter {
|
|||||||
*/
|
*/
|
||||||
public EffectPlayer getEffect(String key)
|
public EffectPlayer getEffect(String key)
|
||||||
{
|
{
|
||||||
EffectPlayer p = effects.get(key);
|
final EffectPlayer p = effects.get(key);
|
||||||
if (p == null) {
|
if (p == null) {
|
||||||
Log.w("Requesting unknown sound effect \"" + key + "\".");
|
Log.w("Requesting unknown sound effect \"" + key + "\".");
|
||||||
return NULL_EFFECT;
|
return NULL_EFFECT;
|
||||||
|
|||||||
@@ -88,7 +88,7 @@ public class SoundSystem extends Subsystem implements Updateable {
|
|||||||
@Override
|
@Override
|
||||||
public final void deinit()
|
public final void deinit()
|
||||||
{
|
{
|
||||||
for (DeferredAudio r : resources) {
|
for (final DeferredAudio r : resources) {
|
||||||
r.destroy();
|
r.destroy();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,7 +100,7 @@ public class SoundSystem extends Subsystem implements Updateable {
|
|||||||
@Override
|
@Override
|
||||||
public void update(double delta)
|
public void update(double delta)
|
||||||
{
|
{
|
||||||
for (Updateable lp : loopPlayers) {
|
for (final Updateable lp : loopPlayers) {
|
||||||
lp.update(delta);
|
lp.update(delta);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -132,7 +132,7 @@ public class SoundSystem extends Subsystem implements Updateable {
|
|||||||
*/
|
*/
|
||||||
public LoopPlayer createLoop(String resource, double pitch, double gain, double fadeIn, double fadeOut)
|
public LoopPlayer createLoop(String resource, double pitch, double gain, double fadeIn, double fadeOut)
|
||||||
{
|
{
|
||||||
LoopPlayer p = new LoopPlayer(getResource(resource), pitch, gain, loopsVolume);
|
final LoopPlayer p = new LoopPlayer(getResource(resource), pitch, gain, loopsVolume);
|
||||||
p.setFadeTimes(fadeIn, fadeOut);
|
p.setFadeTimes(fadeIn, fadeOut);
|
||||||
loopPlayers.add(p);
|
loopPlayers.add(p);
|
||||||
return p;
|
return p;
|
||||||
@@ -148,7 +148,7 @@ public class SoundSystem extends Subsystem implements Updateable {
|
|||||||
*/
|
*/
|
||||||
private DeferredAudio getResource(String res)
|
private DeferredAudio getResource(String res)
|
||||||
{
|
{
|
||||||
DeferredAudio a = new DeferredAudio(res);
|
final DeferredAudio a = new DeferredAudio(res);
|
||||||
bus().queue(new ResourceLoadRequest(a));
|
bus().queue(new ResourceLoadRequest(a));
|
||||||
|
|
||||||
if (resources.contains(a)) throw new IllegalArgumentException("Sound resource " + res + " is already registered.");
|
if (resources.contains(a)) throw new IllegalArgumentException("Sound resource " + res + " is already registered.");
|
||||||
@@ -162,7 +162,7 @@ public class SoundSystem extends Subsystem implements Updateable {
|
|||||||
*/
|
*/
|
||||||
public void fadeOutAllLoops()
|
public void fadeOutAllLoops()
|
||||||
{
|
{
|
||||||
for (LoopPlayer p : loopPlayers) {
|
for (final LoopPlayer p : loopPlayers) {
|
||||||
p.fadeOut();
|
p.fadeOut();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -173,7 +173,7 @@ public class SoundSystem extends Subsystem implements Updateable {
|
|||||||
*/
|
*/
|
||||||
public void pauseAllLoops()
|
public void pauseAllLoops()
|
||||||
{
|
{
|
||||||
for (LoopPlayer p : loopPlayers) {
|
for (final LoopPlayer p : loopPlayers) {
|
||||||
p.pause();
|
p.pause();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -92,7 +92,7 @@ public class LoopPlayer extends BaseAudioPlayer implements Updateable, Pauseable
|
|||||||
|
|
||||||
fadeAnim.update(delta);
|
fadeAnim.update(delta);
|
||||||
|
|
||||||
double gain = getGain(fadeAnim.now());
|
final double gain = getGain(fadeAnim.now());
|
||||||
if (!paused && gain != lastUpdateGain) {
|
if (!paused && gain != lastUpdateGain) {
|
||||||
AL10.alSourcef(sourceID, AL10.AL_GAIN, (float) gain);
|
AL10.alSourcef(sourceID, AL10.AL_GAIN, (float) gain);
|
||||||
lastUpdateGain = gain;
|
lastUpdateGain = gain;
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import mightypork.utils.logging.Log;
|
|||||||
|
|
||||||
public class TaskTakeScreenshot implements Runnable {
|
public class TaskTakeScreenshot implements Runnable {
|
||||||
|
|
||||||
private Screenshot scr;
|
private final Screenshot scr;
|
||||||
|
|
||||||
|
|
||||||
public TaskTakeScreenshot(DisplaySystem disp) {
|
public TaskTakeScreenshot(DisplaySystem disp) {
|
||||||
@@ -30,20 +30,20 @@ public class TaskTakeScreenshot implements Runnable {
|
|||||||
public void run()
|
public void run()
|
||||||
{
|
{
|
||||||
|
|
||||||
BufferedImage image = new BufferedImage(scr.width, scr.height, BufferedImage.TYPE_INT_RGB);
|
final BufferedImage image = new BufferedImage(scr.width, scr.height, BufferedImage.TYPE_INT_RGB);
|
||||||
|
|
||||||
// convert to a buffered image
|
// convert to a buffered image
|
||||||
for (int x = 0; x < scr.width; x++) {
|
for (int x = 0; x < scr.width; x++) {
|
||||||
for (int y = 0; y < scr.height; y++) {
|
for (int y = 0; y < scr.height; y++) {
|
||||||
int i = (x + (scr.width * y)) * scr.bpp;
|
final int i = (x + (scr.width * y)) * scr.bpp;
|
||||||
int r = scr.bytes.get(i) & 0xFF;
|
final int r = scr.bytes.get(i) & 0xFF;
|
||||||
int g = scr.bytes.get(i + 1) & 0xFF;
|
final int g = scr.bytes.get(i + 1) & 0xFF;
|
||||||
int b = scr.bytes.get(i + 2) & 0xFF;
|
final int b = scr.bytes.get(i + 2) & 0xFF;
|
||||||
image.setRGB(x, scr.height - (y + 1), (0xFF << 24) | (r << 16) | (g << 8) | b);
|
image.setRGB(x, scr.height - (y + 1), (0xFF << 24) | (r << 16) | (g << 8) | b);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
String fname = getUniqueScreenshotName();
|
final String fname = getUniqueScreenshotName();
|
||||||
|
|
||||||
// generate unique filename
|
// generate unique filename
|
||||||
File file;
|
File file;
|
||||||
@@ -56,12 +56,12 @@ public class TaskTakeScreenshot implements Runnable {
|
|||||||
|
|
||||||
Log.f3("Saving screenshot to file: " + file);
|
Log.f3("Saving screenshot to file: " + file);
|
||||||
|
|
||||||
String format = "PNG";
|
final String format = "PNG";
|
||||||
|
|
||||||
// save to disk
|
// save to disk
|
||||||
try {
|
try {
|
||||||
ImageIO.write(image, format, file);
|
ImageIO.write(image, format, file);
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
Log.e("Failed to save screenshot.", e);
|
Log.e("Failed to save screenshot.", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -69,7 +69,7 @@ public class TaskTakeScreenshot implements Runnable {
|
|||||||
|
|
||||||
private static String getUniqueScreenshotName()
|
private static String getUniqueScreenshotName()
|
||||||
{
|
{
|
||||||
DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
|
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
|
||||||
return df.format(new Date());
|
return df.format(new Date());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+4
-3
@@ -1,7 +1,7 @@
|
|||||||
package mightypork.rogue.texture;
|
package mightypork.rogue.textures;
|
||||||
|
|
||||||
|
|
||||||
import mightypork.rogue.loading.DeferredResource;
|
import mightypork.rogue.loading.BaseDeferredResource;
|
||||||
import mightypork.rogue.loading.MustLoadInMainThread;
|
import mightypork.rogue.loading.MustLoadInMainThread;
|
||||||
import mightypork.rogue.render.Render;
|
import mightypork.rogue.render.Render;
|
||||||
import mightypork.utils.math.coord.Rect;
|
import mightypork.utils.math.coord.Rect;
|
||||||
@@ -15,7 +15,8 @@ import org.newdawn.slick.opengl.Texture;
|
|||||||
*
|
*
|
||||||
* @author MightyPork
|
* @author MightyPork
|
||||||
*/
|
*/
|
||||||
public class DeferredTexture extends DeferredResource implements FilteredTexture, MustLoadInMainThread {
|
@MustLoadInMainThread
|
||||||
|
public class DeferredTexture extends BaseDeferredResource implements FilteredTexture {
|
||||||
|
|
||||||
private Texture backingTexture;
|
private Texture backingTexture;
|
||||||
private Filter filter_min = Filter.LINEAR;
|
private Filter filter_min = Filter.LINEAR;
|
||||||
+4
-4
@@ -1,4 +1,4 @@
|
|||||||
package mightypork.rogue.texture;
|
package mightypork.rogue.textures;
|
||||||
|
|
||||||
|
|
||||||
import org.lwjgl.opengl.GL11;
|
import org.lwjgl.opengl.GL11;
|
||||||
@@ -38,7 +38,7 @@ public interface FilteredTexture extends Texture {
|
|||||||
* @param filterMin downscale filter
|
* @param filterMin downscale filter
|
||||||
* @param filterMag upscale filter
|
* @param filterMag upscale filter
|
||||||
*/
|
*/
|
||||||
public void setFilter(Filter filterMin, Filter filterMag);
|
void setFilter(Filter filterMin, Filter filterMag);
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -46,11 +46,11 @@ public interface FilteredTexture extends Texture {
|
|||||||
*
|
*
|
||||||
* @param filter filter
|
* @param filter filter
|
||||||
*/
|
*/
|
||||||
public void setFilter(Filter filter);
|
void setFilter(Filter filter);
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param wrapping wrap mode
|
* @param wrapping wrap mode
|
||||||
*/
|
*/
|
||||||
public void setWrap(Wrap wrapping);
|
void setWrap(Wrap wrapping);
|
||||||
}
|
}
|
||||||
+10
-10
@@ -1,4 +1,4 @@
|
|||||||
package mightypork.rogue.texture;
|
package mightypork.rogue.textures;
|
||||||
|
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
@@ -6,8 +6,8 @@ import java.util.HashMap;
|
|||||||
import mightypork.rogue.AppAccess;
|
import mightypork.rogue.AppAccess;
|
||||||
import mightypork.rogue.AppAdapter;
|
import mightypork.rogue.AppAdapter;
|
||||||
import mightypork.rogue.bus.events.ResourceLoadRequest;
|
import mightypork.rogue.bus.events.ResourceLoadRequest;
|
||||||
import mightypork.rogue.texture.FilteredTexture.Filter;
|
import mightypork.rogue.textures.FilteredTexture.Filter;
|
||||||
import mightypork.rogue.texture.FilteredTexture.Wrap;
|
import mightypork.rogue.textures.FilteredTexture.Wrap;
|
||||||
import mightypork.utils.math.coord.Rect;
|
import mightypork.utils.math.coord.Rect;
|
||||||
|
|
||||||
import org.newdawn.slick.opengl.Texture;
|
import org.newdawn.slick.opengl.Texture;
|
||||||
@@ -54,7 +54,7 @@ public class TextureBank extends AppAdapter {
|
|||||||
*/
|
*/
|
||||||
public void loadTexture(String key, String resourcePath, Filter filter_min, Filter filter_mag, Wrap wrap)
|
public void loadTexture(String key, String resourcePath, Filter filter_min, Filter filter_mag, Wrap wrap)
|
||||||
{
|
{
|
||||||
DeferredTexture tx = new DeferredTexture(resourcePath);
|
final DeferredTexture tx = new DeferredTexture(resourcePath);
|
||||||
tx.setFilter(filter_min, filter_mag);
|
tx.setFilter(filter_min, filter_mag);
|
||||||
tx.setWrap(wrap);
|
tx.setWrap(wrap);
|
||||||
|
|
||||||
@@ -74,10 +74,10 @@ public class TextureBank extends AppAdapter {
|
|||||||
*/
|
*/
|
||||||
public void makeQuad(String quadKey, String textureKey, Rect quad)
|
public void makeQuad(String quadKey, String textureKey, Rect quad)
|
||||||
{
|
{
|
||||||
DeferredTexture tx = textures.get(textureKey);
|
final DeferredTexture tx = textures.get(textureKey);
|
||||||
if (tx == null) throw new RuntimeException("Texture with key " + textureKey + " not defined!");
|
if (tx == null) throw new RuntimeException("Texture with key " + textureKey + " not defined!");
|
||||||
|
|
||||||
TxQuad txquad = tx.getQuad(quad);
|
final TxQuad txquad = tx.getQuad(quad);
|
||||||
|
|
||||||
quads.put(quadKey, txquad);
|
quads.put(quadKey, txquad);
|
||||||
}
|
}
|
||||||
@@ -91,10 +91,10 @@ public class TextureBank extends AppAdapter {
|
|||||||
*/
|
*/
|
||||||
public void makeQuad(String quadKey, Rect quad)
|
public void makeQuad(String quadKey, Rect quad)
|
||||||
{
|
{
|
||||||
DeferredTexture tx = lastTx;
|
final DeferredTexture tx = lastTx;
|
||||||
if (tx == null) throw new RuntimeException("There's no texture loaded yet, can't define quads!");
|
if (tx == null) throw new RuntimeException("There's no texture loaded yet, can't define quads!");
|
||||||
|
|
||||||
TxQuad txquad = tx.getQuad(quad);
|
final TxQuad txquad = tx.getQuad(quad);
|
||||||
|
|
||||||
quads.put(quadKey, txquad);
|
quads.put(quadKey, txquad);
|
||||||
}
|
}
|
||||||
@@ -108,7 +108,7 @@ public class TextureBank extends AppAdapter {
|
|||||||
*/
|
*/
|
||||||
public TxQuad getTxQuad(String key)
|
public TxQuad getTxQuad(String key)
|
||||||
{
|
{
|
||||||
TxQuad q = quads.get(key);
|
final TxQuad q = quads.get(key);
|
||||||
|
|
||||||
if (q == null) throw new RuntimeException("There's no quad called " + key + "!");
|
if (q == null) throw new RuntimeException("There's no quad called " + key + "!");
|
||||||
|
|
||||||
@@ -124,7 +124,7 @@ public class TextureBank extends AppAdapter {
|
|||||||
*/
|
*/
|
||||||
public Texture getTexture(String key)
|
public Texture getTexture(String key)
|
||||||
{
|
{
|
||||||
Texture t = textures.get(key);
|
final Texture t = textures.get(key);
|
||||||
|
|
||||||
if (t == null) throw new RuntimeException("There's no texture called " + key + "!");
|
if (t == null) throw new RuntimeException("There's no texture called " + key + "!");
|
||||||
|
|
||||||
+3
-3
@@ -1,4 +1,4 @@
|
|||||||
package mightypork.rogue.texture;
|
package mightypork.rogue.textures;
|
||||||
|
|
||||||
|
|
||||||
import mightypork.utils.math.coord.Rect;
|
import mightypork.utils.math.coord.Rect;
|
||||||
@@ -31,8 +31,8 @@ public class TxQuad {
|
|||||||
*/
|
*/
|
||||||
public static TxQuad fromSizePx(Texture tx, double xPx, double yPx, double widthPx, double heightPx)
|
public static TxQuad fromSizePx(Texture tx, double xPx, double yPx, double widthPx, double heightPx)
|
||||||
{
|
{
|
||||||
double w = tx.getImageWidth();
|
final double w = tx.getImageWidth();
|
||||||
double h = tx.getImageHeight();
|
final double h = tx.getImageHeight();
|
||||||
|
|
||||||
return fromSize(tx, xPx / w, yPx / h, widthPx / w, heightPx / h);
|
return fromSize(tx, xPx / w, yPx / h, widthPx / w, heightPx / h);
|
||||||
}
|
}
|
||||||
@@ -10,7 +10,7 @@ public class Utils {
|
|||||||
|
|
||||||
public static Thread runAsThread(Runnable r)
|
public static Thread runAsThread(Runnable r)
|
||||||
{
|
{
|
||||||
Thread t = new Thread(r);
|
final Thread t = new Thread(r);
|
||||||
t.start();
|
t.start();
|
||||||
return t;
|
return t;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,8 +16,8 @@ import java.util.List;
|
|||||||
*/
|
*/
|
||||||
public class BufferedHashSet<E> extends HashSet<E> {
|
public class BufferedHashSet<E> extends HashSet<E> {
|
||||||
|
|
||||||
private List<E> toAdd = new LinkedList<E>();
|
private final List<E> toAdd = new LinkedList<E>();
|
||||||
private List<Object> toRemove = new LinkedList<Object>();
|
private final List<Object> toRemove = new LinkedList<Object>();
|
||||||
private boolean buffering = false;
|
private boolean buffering = false;
|
||||||
|
|
||||||
|
|
||||||
@@ -72,11 +72,11 @@ public class BufferedHashSet<E> extends HashSet<E> {
|
|||||||
*/
|
*/
|
||||||
private void flush()
|
private void flush()
|
||||||
{
|
{
|
||||||
for (E e : toAdd) {
|
for (final E e : toAdd) {
|
||||||
super.add(e);
|
super.add(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (Object e : toRemove) {
|
for (final Object e : toRemove) {
|
||||||
super.remove(e);
|
super.remove(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,16 +17,16 @@ import mightypork.utils.logging.Log;
|
|||||||
final public class EventBus implements Destroyable {
|
final public class EventBus implements Destroyable {
|
||||||
|
|
||||||
/** Message channels */
|
/** Message channels */
|
||||||
private BufferedHashSet<EventChannel<?, ?>> channels = new BufferedHashSet<EventChannel<?, ?>>();
|
private final BufferedHashSet<EventChannel<?, ?>> channels = new BufferedHashSet<EventChannel<?, ?>>();
|
||||||
|
|
||||||
/** Registered clients */
|
/** Registered clients */
|
||||||
private BufferedHashSet<Object> clients = new BufferedHashSet<Object>();
|
private final BufferedHashSet<Object> clients = new BufferedHashSet<Object>();
|
||||||
|
|
||||||
/** Messages queued for delivery */
|
/** Messages queued for delivery */
|
||||||
private DelayQueue<DelayedMessage> sendQueue = new DelayQueue<DelayedMessage>();
|
private final DelayQueue<DelayedMessage> sendQueue = new DelayQueue<DelayedMessage>();
|
||||||
|
|
||||||
/** Queue polling thread */
|
/** Queue polling thread */
|
||||||
private QueuePollingThread busThread;
|
private final QueuePollingThread busThread;
|
||||||
|
|
||||||
/** Log all */
|
/** Log all */
|
||||||
private boolean logging = false;
|
private boolean logging = false;
|
||||||
@@ -55,7 +55,7 @@ final public class EventBus implements Destroyable {
|
|||||||
|
|
||||||
logging = level;
|
logging = level;
|
||||||
|
|
||||||
for (EventChannel<?, ?> ch : channels) {
|
for (final EventChannel<?, ?> ch : channels) {
|
||||||
ch.enableLogging(logging);
|
ch.enableLogging(logging);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -73,7 +73,7 @@ final public class EventBus implements Destroyable {
|
|||||||
assertLive();
|
assertLive();
|
||||||
|
|
||||||
// if the channel already exists, return this instance instead.
|
// if the channel already exists, return this instance instead.
|
||||||
for (EventChannel<?, ?> ch : channels) {
|
for (final EventChannel<?, ?> ch : channels) {
|
||||||
if (ch.equals(channel)) {
|
if (ch.equals(channel)) {
|
||||||
Log.w("<bus> Channel of type " + Log.str(channel) + " already registered.");
|
Log.w("<bus> Channel of type " + Log.str(channel) + " already registered.");
|
||||||
return ch;
|
return ch;
|
||||||
@@ -99,7 +99,7 @@ final public class EventBus implements Destroyable {
|
|||||||
{
|
{
|
||||||
assertLive();
|
assertLive();
|
||||||
|
|
||||||
EventChannel<F_EVENT, F_CLIENT> channel = EventChannel.create(messageClass, clientClass);
|
final EventChannel<F_EVENT, F_CLIENT> channel = EventChannel.create(messageClass, clientClass);
|
||||||
return addChannel(channel);
|
return addChannel(channel);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,7 +140,7 @@ final public class EventBus implements Destroyable {
|
|||||||
{
|
{
|
||||||
assertLive();
|
assertLive();
|
||||||
|
|
||||||
DelayedMessage dm = new DelayedMessage(delay, message);
|
final DelayedMessage dm = new DelayedMessage(delay, message);
|
||||||
|
|
||||||
if (logging) Log.f3("<bus> + [ Queuing: " + Log.str(message) + " ]");
|
if (logging) Log.f3("<bus> + [ Queuing: " + Log.str(message) + " ]");
|
||||||
|
|
||||||
@@ -168,9 +168,17 @@ final public class EventBus implements Destroyable {
|
|||||||
boolean sent = false;
|
boolean sent = false;
|
||||||
boolean channelAccepted = false;
|
boolean channelAccepted = false;
|
||||||
|
|
||||||
for (EventChannel<?, ?> b : channels) {
|
final boolean singular = message.getClass().isAnnotationPresent(SingularEvent.class);
|
||||||
if (b.canBroadcast(message)) channelAccepted = true;
|
|
||||||
sent |= b.broadcast(message, clients);
|
for (final EventChannel<?, ?> b : channels) {
|
||||||
|
if (b.canBroadcast(message)) {
|
||||||
|
channelAccepted = true;
|
||||||
|
sent |= b.broadcast(message, clients);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sent && singular) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// more severe
|
// more severe
|
||||||
@@ -224,7 +232,7 @@ final public class EventBus implements Destroyable {
|
|||||||
|
|
||||||
if (client == null) return false;
|
if (client == null) return false;
|
||||||
|
|
||||||
for (EventChannel<?, ?> ch : channels) {
|
for (final EventChannel<?, ?> ch : channels) {
|
||||||
if (ch.isClientValid(client)) {
|
if (ch.isClientValid(client)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -235,7 +243,7 @@ final public class EventBus implements Destroyable {
|
|||||||
|
|
||||||
private class DelayedMessage implements Delayed {
|
private class DelayedMessage implements Delayed {
|
||||||
|
|
||||||
private long due;
|
private final long due;
|
||||||
private Event<?> theMessage = null;
|
private Event<?> theMessage = null;
|
||||||
|
|
||||||
|
|
||||||
@@ -287,7 +295,7 @@ final public class EventBus implements Destroyable {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
dm = sendQueue.take();
|
dm = sendQueue.take();
|
||||||
} catch (InterruptedException ignored) {
|
} catch (final InterruptedException ignored) {
|
||||||
//
|
//
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,8 +18,8 @@ import mightypork.utils.logging.Log;
|
|||||||
*/
|
*/
|
||||||
final public class EventChannel<EVENT extends Event<CLIENT>, CLIENT> {
|
final public class EventChannel<EVENT extends Event<CLIENT>, CLIENT> {
|
||||||
|
|
||||||
private Class<CLIENT> clientClass;
|
private final Class<CLIENT> clientClass;
|
||||||
private Class<EVENT> messageClass;
|
private final Class<EVENT> messageClass;
|
||||||
private boolean logging = false;
|
private boolean logging = false;
|
||||||
|
|
||||||
|
|
||||||
@@ -61,7 +61,7 @@ final public class EventChannel<EVENT extends Event<CLIENT>, CLIENT> {
|
|||||||
{
|
{
|
||||||
if (!canBroadcast(message)) return false;
|
if (!canBroadcast(message)) return false;
|
||||||
|
|
||||||
EVENT evt = messageClass.cast(message);
|
final EVENT evt = messageClass.cast(message);
|
||||||
|
|
||||||
return doBroadcast(evt, clients, new HashSet<Object>());
|
return doBroadcast(evt, clients, new HashSet<Object>());
|
||||||
}
|
}
|
||||||
@@ -78,8 +78,9 @@ final public class EventChannel<EVENT extends Event<CLIENT>, CLIENT> {
|
|||||||
private boolean doBroadcast(final EVENT message, final Collection<Object> clients, final Collection<Object> processed)
|
private boolean doBroadcast(final EVENT message, final Collection<Object> clients, final Collection<Object> processed)
|
||||||
{
|
{
|
||||||
boolean sent = false;
|
boolean sent = false;
|
||||||
|
final boolean singular = message.getClass().isAnnotationPresent(SingularEvent.class);
|
||||||
|
|
||||||
for (Object client : clients) {
|
for (final Object client : clients) {
|
||||||
|
|
||||||
// exclude obvious non-clients
|
// exclude obvious non-clients
|
||||||
if (!isClientValid(client)) {
|
if (!isClientValid(client)) {
|
||||||
@@ -104,13 +105,13 @@ final public class EventChannel<EVENT extends Event<CLIENT>, CLIENT> {
|
|||||||
sent |= sendTo(client, message);
|
sent |= sendTo(client, message);
|
||||||
|
|
||||||
// singular event ain't no whore, handled once only.
|
// singular event ain't no whore, handled once only.
|
||||||
if (sent && message instanceof SingularEvent) return true;
|
if (sent && singular) return true;
|
||||||
|
|
||||||
// pass on to delegated clients
|
// pass on to delegated clients
|
||||||
if (client instanceof DelegatingClient) {
|
if (client instanceof DelegatingClient) {
|
||||||
if (((DelegatingClient) client).doesDelegate()) {
|
if (((DelegatingClient) client).doesDelegate()) {
|
||||||
|
|
||||||
Collection<Object> children = ((DelegatingClient) client).getChildClients();
|
final Collection<Object> children = ((DelegatingClient) client).getChildClients();
|
||||||
|
|
||||||
if (children != null && children.size() > 0) {
|
if (children != null && children.size() > 0) {
|
||||||
sent |= doBroadcast(message, children, processed);
|
sent |= doBroadcast(message, children, processed);
|
||||||
@@ -212,7 +213,7 @@ final public class EventChannel<EVENT extends Event<CLIENT>, CLIENT> {
|
|||||||
if (this == obj) return true;
|
if (this == obj) return true;
|
||||||
if (obj == null) return false;
|
if (obj == null) return false;
|
||||||
if (!(obj instanceof EventChannel)) return false;
|
if (!(obj instanceof EventChannel)) return false;
|
||||||
EventChannel<?, ?> other = (EventChannel<?, ?>) obj;
|
final EventChannel<?, ?> other = (EventChannel<?, ?>) obj;
|
||||||
if (clientClass == null) {
|
if (clientClass == null) {
|
||||||
if (other.clientClass != null) return false;
|
if (other.clientClass != null) return false;
|
||||||
} else if (!clientClass.equals(other.clientClass)) return false;
|
} else if (!clientClass.equals(other.clientClass)) return false;
|
||||||
|
|||||||
@@ -1,11 +1,17 @@
|
|||||||
package mightypork.utils.control.bus;
|
package mightypork.utils.control.bus;
|
||||||
|
|
||||||
|
|
||||||
|
import java.lang.annotation.*;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Event handled by only single client.
|
* Event that is handled by only single client, and then discarded (ie. only one
|
||||||
|
* client receives it when it's broadcasted).
|
||||||
*
|
*
|
||||||
* @author MightyPork
|
* @author MightyPork
|
||||||
*/
|
*/
|
||||||
public interface SingularEvent {
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
@Target(ElementType.TYPE)
|
||||||
}
|
@Inherited
|
||||||
|
@Documented
|
||||||
|
public @interface SingularEvent {}
|
||||||
|
|||||||
@@ -39,8 +39,8 @@ public class TimerDelta {
|
|||||||
*/
|
*/
|
||||||
public double getDelta()
|
public double getDelta()
|
||||||
{
|
{
|
||||||
long time = getTime();
|
final long time = getTime();
|
||||||
double delta = (time - lastFrame) / (double) SECOND;
|
final double delta = (time - lastFrame) / (double) SECOND;
|
||||||
lastFrame = time;
|
lastFrame = time;
|
||||||
return delta;
|
return delta;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ public class TimerFps {
|
|||||||
private long lastSkipped = 0;
|
private long lastSkipped = 0;
|
||||||
|
|
||||||
private static final long SECOND = 1000000000; // a million nanoseconds
|
private static final long SECOND = 1000000000; // a million nanoseconds
|
||||||
private long FRAME; // a time of one frame in nanoseconds
|
private final long FRAME; // a time of one frame in nanoseconds
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -35,9 +35,9 @@ public class TimerFps {
|
|||||||
*/
|
*/
|
||||||
public void sync()
|
public void sync()
|
||||||
{
|
{
|
||||||
long time = getTime();
|
final long time = getTime();
|
||||||
if (time >= nextFrame) {
|
if (time >= nextFrame) {
|
||||||
long skippedNow = (long) Math.floor((time - nextFrame) / (double) FRAME) + 1;
|
final long skippedNow = (long) Math.floor((time - nextFrame) / (double) FRAME) + 1;
|
||||||
skipped += skippedNow;
|
skipped += skippedNow;
|
||||||
lastFrame = nextFrame + (1 - skippedNow) * FRAME;
|
lastFrame = nextFrame + (1 - skippedNow) * FRAME;
|
||||||
nextFrame += skippedNow * FRAME;
|
nextFrame += skippedNow * FRAME;
|
||||||
@@ -67,7 +67,7 @@ public class TimerFps {
|
|||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
long time = getTime();
|
final long time = getTime();
|
||||||
|
|
||||||
if (time <= nextFrame) {
|
if (time <= nextFrame) {
|
||||||
return (double) (time - lastFrame) / (double) FRAME;
|
return (double) (time - lastFrame) / (double) FRAME;
|
||||||
@@ -84,7 +84,7 @@ public class TimerFps {
|
|||||||
*/
|
*/
|
||||||
public int getSkipped()
|
public int getSkipped()
|
||||||
{
|
{
|
||||||
long change = skipped - lastSkipped;
|
final long change = skipped - lastSkipped;
|
||||||
lastSkipped = skipped;
|
lastSkipped = skipped;
|
||||||
return (int) change;
|
return (int) change;
|
||||||
}
|
}
|
||||||
@@ -95,7 +95,7 @@ public class TimerFps {
|
|||||||
*/
|
*/
|
||||||
public void startNewFrame()
|
public void startNewFrame()
|
||||||
{
|
{
|
||||||
long time = getTime();
|
final long time = getTime();
|
||||||
lastFrame = time;
|
lastFrame = time;
|
||||||
nextFrame = time + FRAME;
|
nextFrame = time + FRAME;
|
||||||
lastSkipped = skipped;
|
lastSkipped = skipped;
|
||||||
|
|||||||
@@ -18,13 +18,13 @@ import mightypork.utils.logging.Log;
|
|||||||
public class FileTreeDiff {
|
public class FileTreeDiff {
|
||||||
|
|
||||||
private static final byte[] BUFFER = new byte[2048];
|
private static final byte[] BUFFER = new byte[2048];
|
||||||
private Checksum ck1 = new Adler32();
|
private final Checksum ck1 = new Adler32();
|
||||||
private Checksum ck2 = new Adler32();
|
private final Checksum ck2 = new Adler32();
|
||||||
|
|
||||||
private boolean logging = true;
|
private boolean logging = true;
|
||||||
|
|
||||||
private List<Tuple<File>> compared = new ArrayList<Tuple<File>>();
|
private final List<Tuple<File>> compared = new ArrayList<Tuple<File>>();
|
||||||
private Comparator<File> fileFirstSorter = new Comparator<File>() {
|
private final Comparator<File> fileFirstSorter = new Comparator<File>() {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int compare(File o1, File o2)
|
public int compare(File o1, File o2)
|
||||||
@@ -57,7 +57,7 @@ public class FileTreeDiff {
|
|||||||
|
|
||||||
return true;
|
return true;
|
||||||
|
|
||||||
} catch (NotEqualException e) {
|
} catch (final NotEqualException e) {
|
||||||
if (logging) Log.f3("Difference found:\n" + e.getMessage());
|
if (logging) Log.f3("Difference found:\n" + e.getMessage());
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
@@ -70,7 +70,7 @@ public class FileTreeDiff {
|
|||||||
FileInputStream in1 = null, in2 = null;
|
FileInputStream in1 = null, in2 = null;
|
||||||
CheckedInputStream cin1 = null, cin2 = null;
|
CheckedInputStream cin1 = null, cin2 = null;
|
||||||
|
|
||||||
for (Tuple<File> pair : compared) {
|
for (final Tuple<File> pair : compared) {
|
||||||
try {
|
try {
|
||||||
ck1.reset();
|
ck1.reset();
|
||||||
ck2.reset();
|
ck2.reset();
|
||||||
@@ -82,8 +82,8 @@ public class FileTreeDiff {
|
|||||||
cin2 = new CheckedInputStream(in2, ck2);
|
cin2 = new CheckedInputStream(in2, ck2);
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
int read1 = cin1.read(BUFFER);
|
final int read1 = cin1.read(BUFFER);
|
||||||
int read2 = cin2.read(BUFFER);
|
final int read2 = cin2.read(BUFFER);
|
||||||
|
|
||||||
if (read1 != read2 || ck1.getValue() != ck2.getValue()) {
|
if (read1 != read2 || ck1.getValue() != ck2.getValue()) {
|
||||||
throw new NotEqualException("Bytes differ:\n" + pair.a + "\n" + pair.b);
|
throw new NotEqualException("Bytes differ:\n" + pair.a + "\n" + pair.b);
|
||||||
@@ -92,31 +92,31 @@ public class FileTreeDiff {
|
|||||||
if (read1 == -1) break;
|
if (read1 == -1) break;
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
// ignore
|
// ignore
|
||||||
} finally {
|
} finally {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (cin1 != null) cin1.close();
|
if (cin1 != null) cin1.close();
|
||||||
} catch (Exception e) {
|
} catch (final Exception e) {
|
||||||
// ignore
|
// ignore
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (cin2 != null) cin2.close();
|
if (cin2 != null) cin2.close();
|
||||||
} catch (Exception e) {
|
} catch (final Exception e) {
|
||||||
// ignore
|
// ignore
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (in1 != null) in1.close();
|
if (in1 != null) in1.close();
|
||||||
} catch (Exception e) {
|
} catch (final Exception e) {
|
||||||
// ignore
|
// ignore
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (in2 != null) in2.close();
|
if (in2 != null) in2.close();
|
||||||
} catch (Exception e) {
|
} catch (final Exception e) {
|
||||||
// ignore
|
// ignore
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,8 +134,8 @@ public class FileTreeDiff {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (f1.isDirectory()) {
|
if (f1.isDirectory()) {
|
||||||
File[] children1 = f1.listFiles();
|
final File[] children1 = f1.listFiles();
|
||||||
File[] children2 = f2.listFiles();
|
final File[] children2 = f2.listFiles();
|
||||||
|
|
||||||
Arrays.sort(children1, fileFirstSorter);
|
Arrays.sort(children1, fileFirstSorter);
|
||||||
Arrays.sort(children2, fileFirstSorter);
|
Arrays.sort(children2, fileFirstSorter);
|
||||||
@@ -143,8 +143,8 @@ public class FileTreeDiff {
|
|||||||
if (children1.length != children2.length) throw new NotEqualException("Child counts differ:\n" + f1 + "\n" + f2);
|
if (children1.length != children2.length) throw new NotEqualException("Child counts differ:\n" + f1 + "\n" + f2);
|
||||||
|
|
||||||
for (int i = 0; i < children1.length; i++) {
|
for (int i = 0; i < children1.length; i++) {
|
||||||
File ch1 = children1[i];
|
final File ch1 = children1[i];
|
||||||
File ch2 = children2[i];
|
final File ch2 = children2[i];
|
||||||
|
|
||||||
if (!ch1.getName().equals(ch2.getName())) throw new NotEqualException("Filenames differ:\n" + ch1 + "\n" + ch2);
|
if (!ch1.getName().equals(ch2.getName())) throw new NotEqualException("Filenames differ:\n" + ch1 + "\n" + ch2);
|
||||||
|
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ public class FileUtils {
|
|||||||
target.mkdir();
|
target.mkdir();
|
||||||
}
|
}
|
||||||
|
|
||||||
String[] children = source.list();
|
final String[] children = source.list();
|
||||||
for (int i = 0; i < children.length; i++) {
|
for (int i = 0; i < children.length; i++) {
|
||||||
copyDirectory(new File(source, children[i]), new File(target, children[i]), filter, filesCopied);
|
copyDirectory(new File(source, children[i]), new File(target, children[i]), filter, filesCopied);
|
||||||
}
|
}
|
||||||
@@ -70,7 +70,7 @@ public class FileUtils {
|
|||||||
public static void listDirectoryRecursive(File source, StringFilter filter, List<File> files) throws IOException
|
public static void listDirectoryRecursive(File source, StringFilter filter, List<File> files) throws IOException
|
||||||
{
|
{
|
||||||
if (source.isDirectory()) {
|
if (source.isDirectory()) {
|
||||||
String[] children = source.list();
|
final String[] children = source.list();
|
||||||
for (int i = 0; i < children.length; i++) {
|
for (int i = 0; i < children.length; i++) {
|
||||||
listDirectoryRecursive(new File(source, children[i]), filter, files);
|
listDirectoryRecursive(new File(source, children[i]), filter, files);
|
||||||
}
|
}
|
||||||
@@ -105,12 +105,12 @@ public class FileUtils {
|
|||||||
} finally {
|
} finally {
|
||||||
try {
|
try {
|
||||||
if (in != null) in.close();
|
if (in != null) in.close();
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
if (out != null) out.close();
|
if (out != null) out.close();
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -134,7 +134,7 @@ public class FileUtils {
|
|||||||
throw new NullPointerException("Output stream is null");
|
throw new NullPointerException("Output stream is null");
|
||||||
}
|
}
|
||||||
|
|
||||||
byte[] buf = new byte[2048];
|
final byte[] buf = new byte[2048];
|
||||||
int len;
|
int len;
|
||||||
while ((len = in.read(buf)) > 0) {
|
while ((len = in.read(buf)) > 0) {
|
||||||
out.write(buf, 0, len);
|
out.write(buf, 0, len);
|
||||||
@@ -157,7 +157,7 @@ public class FileUtils {
|
|||||||
|
|
||||||
if (!recursive || !path.isDirectory()) return path.delete();
|
if (!recursive || !path.isDirectory()) return path.delete();
|
||||||
|
|
||||||
String[] list = path.list();
|
final String[] list = path.list();
|
||||||
for (int i = 0; i < list.length; i++) {
|
for (int i = 0; i < list.length; i++) {
|
||||||
if (!delete(new File(path, list[i]), true)) return false;
|
if (!delete(new File(path, list[i]), true)) return false;
|
||||||
}
|
}
|
||||||
@@ -175,7 +175,7 @@ public class FileUtils {
|
|||||||
*/
|
*/
|
||||||
public static String fileToString(File file) throws IOException
|
public static String fileToString(File file) throws IOException
|
||||||
{
|
{
|
||||||
FileInputStream fin = new FileInputStream(file);
|
final FileInputStream fin = new FileInputStream(file);
|
||||||
|
|
||||||
return streamToString(fin);
|
return streamToString(fin);
|
||||||
}
|
}
|
||||||
@@ -204,17 +204,17 @@ public class FileUtils {
|
|||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
dir.mkdir();
|
dir.mkdir();
|
||||||
} catch (RuntimeException e) {
|
} catch (final RuntimeException e) {
|
||||||
Log.e("Error creating folder " + dir, e);
|
Log.e("Error creating folder " + dir, e);
|
||||||
}
|
}
|
||||||
|
|
||||||
List<File> list = new ArrayList<File>();
|
final List<File> list = new ArrayList<File>();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
for (File f : dir.listFiles(filter)) {
|
for (final File f : dir.listFiles(filter)) {
|
||||||
list.add(f);
|
list.add(f);
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (final Exception e) {
|
||||||
Log.e("Error listing folder " + dir, e);
|
Log.e("Error listing folder " + dir, e);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -258,13 +258,13 @@ public class FileUtils {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
ext = StringUtils.fromLastDot(filename);
|
ext = StringUtils.fromLastDot(filename);
|
||||||
} catch (StringIndexOutOfBoundsException e) {
|
} catch (final StringIndexOutOfBoundsException e) {
|
||||||
ext = "";
|
ext = "";
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
name = StringUtils.toLastDot(filename);
|
name = StringUtils.toLastDot(filename);
|
||||||
} catch (StringIndexOutOfBoundsException e) {
|
} catch (final StringIndexOutOfBoundsException e) {
|
||||||
name = "";
|
name = "";
|
||||||
Log.w("Error extracting extension from file " + filename);
|
Log.w("Error extracting extension from file " + filename);
|
||||||
}
|
}
|
||||||
@@ -300,7 +300,7 @@ public class FileUtils {
|
|||||||
}
|
}
|
||||||
|
|
||||||
BufferedReader br = null;
|
BufferedReader br = null;
|
||||||
StringBuilder sb = new StringBuilder();
|
final StringBuilder sb = new StringBuilder();
|
||||||
|
|
||||||
String line;
|
String line;
|
||||||
try {
|
try {
|
||||||
@@ -315,12 +315,12 @@ public class FileUtils {
|
|||||||
sb.append("--- end of preview ---\n");
|
sb.append("--- end of preview ---\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
Log.e(e);
|
Log.e(e);
|
||||||
} finally {
|
} finally {
|
||||||
try {
|
try {
|
||||||
if (br != null) br.close();
|
if (br != null) br.close();
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
// ignore
|
// ignore
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -335,7 +335,7 @@ public class FileUtils {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
return new ByteArrayInputStream(text.getBytes("UTF-8"));
|
return new ByteArrayInputStream(text.getBytes("UTF-8"));
|
||||||
} catch (UnsupportedEncodingException e) {
|
} catch (final UnsupportedEncodingException e) {
|
||||||
Log.e(e);
|
Log.e(e);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -344,13 +344,13 @@ public class FileUtils {
|
|||||||
|
|
||||||
public static InputStream getResource(String path)
|
public static InputStream getResource(String path)
|
||||||
{
|
{
|
||||||
InputStream in = FileUtils.class.getResourceAsStream(path);
|
final InputStream in = FileUtils.class.getResourceAsStream(path);
|
||||||
|
|
||||||
if (in != null) return in;
|
if (in != null) return in;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return new FileInputStream(new File(".", path));
|
return new FileInputStream(new File(".", path));
|
||||||
} catch (FileNotFoundException e) {
|
} catch (final FileNotFoundException e) {
|
||||||
// error
|
// error
|
||||||
Log.w("Could not open resource stream: " + path);
|
Log.w("Could not open resource stream: " + path);
|
||||||
return null;
|
return null;
|
||||||
@@ -390,12 +390,12 @@ public class FileUtils {
|
|||||||
|
|
||||||
public static void deleteEmptyDirs(File base)
|
public static void deleteEmptyDirs(File base)
|
||||||
{
|
{
|
||||||
for (File f : listDirectory(base)) {
|
for (final File f : listDirectory(base)) {
|
||||||
if (!f.isDirectory()) continue;
|
if (!f.isDirectory()) continue;
|
||||||
|
|
||||||
deleteEmptyDirs(f);
|
deleteEmptyDirs(f);
|
||||||
|
|
||||||
List<File> children = listDirectory(f);
|
final List<File> children = listDirectory(f);
|
||||||
if (children.size() == 0) {
|
if (children.size() == 0) {
|
||||||
f.delete();
|
f.delete();
|
||||||
continue;
|
continue;
|
||||||
@@ -413,9 +413,9 @@ public class FileUtils {
|
|||||||
*/
|
*/
|
||||||
public static String escapeFileString(String filestring)
|
public static String escapeFileString(String filestring)
|
||||||
{
|
{
|
||||||
StringBuilder sb = new StringBuilder();
|
final StringBuilder sb = new StringBuilder();
|
||||||
|
|
||||||
for (char c : filestring.toCharArray()) {
|
for (final char c : filestring.toCharArray()) {
|
||||||
switch (c) {
|
switch (c) {
|
||||||
case '%':
|
case '%':
|
||||||
sb.append("%%");
|
sb.append("%%");
|
||||||
@@ -458,7 +458,7 @@ public class FileUtils {
|
|||||||
*/
|
*/
|
||||||
public static String escapeFilename(String filename)
|
public static String escapeFilename(String filename)
|
||||||
{
|
{
|
||||||
String[] parts = getFilenameParts(filename);
|
final String[] parts = getFilenameParts(filename);
|
||||||
|
|
||||||
return escapeFileString(parts[0]) + "." + parts[1];
|
return escapeFileString(parts[0]) + "." + parts[1];
|
||||||
}
|
}
|
||||||
@@ -472,7 +472,7 @@ public class FileUtils {
|
|||||||
*/
|
*/
|
||||||
public static String unescapeFilename(String filename)
|
public static String unescapeFilename(String filename)
|
||||||
{
|
{
|
||||||
String[] parts = getFilenameParts(filename);
|
final String[] parts = getFilenameParts(filename);
|
||||||
|
|
||||||
return unescapeFileString(parts[0]) + "." + parts[1];
|
return unescapeFileString(parts[0]) + "." + parts[1];
|
||||||
}
|
}
|
||||||
@@ -510,13 +510,13 @@ public class FileUtils {
|
|||||||
} finally {
|
} finally {
|
||||||
try {
|
try {
|
||||||
if (in != null) in.close();
|
if (in != null) in.close();
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
// ignore
|
// ignore
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (out != null) out.close();
|
if (out != null) out.close();
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
// ignore
|
// ignore
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -532,7 +532,7 @@ public class FileUtils {
|
|||||||
*/
|
*/
|
||||||
public static String resourceToString(String resname)
|
public static String resourceToString(String resname)
|
||||||
{
|
{
|
||||||
InputStream in = FileUtils.getResource(resname);
|
final InputStream in = FileUtils.getResource(resname);
|
||||||
return streamToString(in);
|
return streamToString(in);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ public class OsUtils {
|
|||||||
*/
|
*/
|
||||||
public static File getWorkDir(String dirname, String subfolderName, boolean create)
|
public static File getWorkDir(String dirname, String subfolderName, boolean create)
|
||||||
{
|
{
|
||||||
File f = new File(getWorkDir(dirname), subfolderName);
|
final File f = new File(getWorkDir(dirname), subfolderName);
|
||||||
|
|
||||||
if (!f.exists() && create) {
|
if (!f.exists() && create) {
|
||||||
if (!f.mkdirs()) {
|
if (!f.mkdirs()) {
|
||||||
@@ -82,7 +82,7 @@ public class OsUtils {
|
|||||||
{
|
{
|
||||||
if (cachedOs != null) return cachedOs;
|
if (cachedOs != null) return cachedOs;
|
||||||
|
|
||||||
String s = System.getProperty("os.name").toLowerCase();
|
final String s = System.getProperty("os.name").toLowerCase();
|
||||||
|
|
||||||
if (s.contains("win")) {
|
if (s.contains("win")) {
|
||||||
cachedOs = EnumOS.windows;
|
cachedOs = EnumOS.windows;
|
||||||
@@ -106,7 +106,7 @@ public class OsUtils {
|
|||||||
|
|
||||||
private static File getWorkDir(String dirname, boolean create)
|
private static File getWorkDir(String dirname, boolean create)
|
||||||
{
|
{
|
||||||
String userhome = System.getProperty("user.home", ".");
|
final String userhome = System.getProperty("user.home", ".");
|
||||||
File file;
|
File file;
|
||||||
|
|
||||||
switch (getOs()) {
|
switch (getOs()) {
|
||||||
@@ -116,7 +116,7 @@ public class OsUtils {
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case windows:
|
case windows:
|
||||||
String appdata = System.getenv("APPDATA");
|
final String appdata = System.getenv("APPDATA");
|
||||||
|
|
||||||
if (appdata != null) {
|
if (appdata != null) {
|
||||||
file = new File(appdata, "." + dirname + '/');
|
file = new File(appdata, "." + dirname + '/');
|
||||||
|
|||||||
@@ -45,16 +45,16 @@ public class PropertyManager {
|
|||||||
|
|
||||||
private static void writeComments(BufferedWriter bw, String comm) throws IOException
|
private static void writeComments(BufferedWriter bw, String comm) throws IOException
|
||||||
{
|
{
|
||||||
String comments = comm.replace("\n\n", "\n \n");
|
final String comments = comm.replace("\n\n", "\n \n");
|
||||||
|
|
||||||
int len = comments.length();
|
final int len = comments.length();
|
||||||
int current = 0;
|
int current = 0;
|
||||||
int last = 0;
|
int last = 0;
|
||||||
char[] uu = new char[6];
|
final char[] uu = new char[6];
|
||||||
uu[0] = '\\';
|
uu[0] = '\\';
|
||||||
uu[1] = 'u';
|
uu[1] = 'u';
|
||||||
while (current < len) {
|
while (current < len) {
|
||||||
char c = comments.charAt(current);
|
final char c = comments.charAt(current);
|
||||||
if (c > '\u00ff' || c == '\n' || c == '\r') {
|
if (c > '\u00ff' || c == '\n' || c == '\r') {
|
||||||
if (last != current) {
|
if (last != current) {
|
||||||
bw.write("# " + comments.substring(last, current));
|
bw.write("# " + comments.substring(last, current));
|
||||||
@@ -96,7 +96,7 @@ public class PropertyManager {
|
|||||||
private boolean firstEntry = true;
|
private boolean firstEntry = true;
|
||||||
|
|
||||||
/** Comments for individual keys */
|
/** Comments for individual keys */
|
||||||
private Hashtable<String, String> keyComments = new Hashtable<String, String>();
|
private final Hashtable<String, String> keyComments = new Hashtable<String, String>();
|
||||||
|
|
||||||
private String lastSectionBeginning = "";
|
private String lastSectionBeginning = "";
|
||||||
|
|
||||||
@@ -105,8 +105,8 @@ public class PropertyManager {
|
|||||||
@Override
|
@Override
|
||||||
public synchronized Enumeration keys()
|
public synchronized Enumeration keys()
|
||||||
{
|
{
|
||||||
Enumeration keysEnum = super.keys();
|
final Enumeration keysEnum = super.keys();
|
||||||
Vector keyList = new Vector();
|
final Vector keyList = new Vector();
|
||||||
while (keysEnum.hasMoreElements()) {
|
while (keysEnum.hasMoreElements()) {
|
||||||
keyList.add(keysEnum.nextElement());
|
keyList.add(keysEnum.nextElement());
|
||||||
}
|
}
|
||||||
@@ -117,15 +117,15 @@ public class PropertyManager {
|
|||||||
|
|
||||||
private static String saveConvert(String theString, boolean escapeSpace, boolean escapeUnicode)
|
private static String saveConvert(String theString, boolean escapeSpace, boolean escapeUnicode)
|
||||||
{
|
{
|
||||||
int len = theString.length();
|
final int len = theString.length();
|
||||||
int bufLen = len * 2;
|
int bufLen = len * 2;
|
||||||
if (bufLen < 0) {
|
if (bufLen < 0) {
|
||||||
bufLen = Integer.MAX_VALUE;
|
bufLen = Integer.MAX_VALUE;
|
||||||
}
|
}
|
||||||
StringBuffer outBuffer = new StringBuffer(bufLen);
|
final StringBuffer outBuffer = new StringBuffer(bufLen);
|
||||||
|
|
||||||
for (int x = 0; x < len; x++) {
|
for (int x = 0; x < len; x++) {
|
||||||
char aChar = theString.charAt(x);
|
final char aChar = theString.charAt(x);
|
||||||
|
|
||||||
// Handle common case first, selecting largest block that
|
// Handle common case first, selecting largest block that
|
||||||
// avoids the specials below
|
// avoids the specials below
|
||||||
@@ -209,16 +209,16 @@ public class PropertyManager {
|
|||||||
@Override
|
@Override
|
||||||
public void store(OutputStream out, String comments) throws IOException
|
public void store(OutputStream out, String comments) throws IOException
|
||||||
{
|
{
|
||||||
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
|
final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
|
||||||
|
|
||||||
boolean escUnicode = false;
|
final boolean escUnicode = false;
|
||||||
|
|
||||||
if (comments != null) {
|
if (comments != null) {
|
||||||
writeComments(bw, comments);
|
writeComments(bw, comments);
|
||||||
}
|
}
|
||||||
|
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
for (Enumeration e = keys(); e.hasMoreElements();) {
|
for (final Enumeration e = keys(); e.hasMoreElements();) {
|
||||||
boolean wasNewLine = false;
|
boolean wasNewLine = false;
|
||||||
|
|
||||||
String key = (String) e.nextElement();
|
String key = (String) e.nextElement();
|
||||||
@@ -242,12 +242,12 @@ public class PropertyManager {
|
|||||||
cm = cm.replace("\r\n", "\n");
|
cm = cm.replace("\r\n", "\n");
|
||||||
cm = cm.replace("\n\n", "\n \n");
|
cm = cm.replace("\n\n", "\n \n");
|
||||||
|
|
||||||
String[] cmlines = cm.split("\n");
|
final String[] cmlines = cm.split("\n");
|
||||||
|
|
||||||
if (!wasNewLine && !firstEntry && cfgEmptyLineBeforeComment) {
|
if (!wasNewLine && !firstEntry && cfgEmptyLineBeforeComment) {
|
||||||
bw.newLine();
|
bw.newLine();
|
||||||
}
|
}
|
||||||
for (String cmline : cmlines) {
|
for (final String cmline : cmlines) {
|
||||||
bw.write("# " + cmline);
|
bw.write("# " + cmline);
|
||||||
bw.newLine();
|
bw.newLine();
|
||||||
}
|
}
|
||||||
@@ -273,11 +273,11 @@ public class PropertyManager {
|
|||||||
|
|
||||||
private static String escapifyStr(String str)
|
private static String escapifyStr(String str)
|
||||||
{
|
{
|
||||||
StringBuilder result = new StringBuilder();
|
final StringBuilder result = new StringBuilder();
|
||||||
|
|
||||||
int len = str.length();
|
final int len = str.length();
|
||||||
for (int x = 0; x < len; x++) {
|
for (int x = 0; x < len; x++) {
|
||||||
char ch = str.charAt(x);
|
final char ch = str.charAt(x);
|
||||||
if (ch <= 0x007e) {
|
if (ch <= 0x007e) {
|
||||||
result.append(ch);
|
result.append(ch);
|
||||||
continue;
|
continue;
|
||||||
@@ -296,7 +296,7 @@ public class PropertyManager {
|
|||||||
|
|
||||||
private static char hexDigit(char ch, int offset)
|
private static char hexDigit(char ch, int offset)
|
||||||
{
|
{
|
||||||
int val = (ch >> offset) & 0xF;
|
final int val = (ch >> offset) & 0xF;
|
||||||
if (val <= 9) {
|
if (val <= 9) {
|
||||||
return (char) ('0' + val);
|
return (char) ('0' + val);
|
||||||
}
|
}
|
||||||
@@ -313,25 +313,25 @@ public class PropertyManager {
|
|||||||
|
|
||||||
public static SortedProperties loadProperties(SortedProperties props, InputStream is, String encoding) throws IOException
|
public static SortedProperties loadProperties(SortedProperties props, InputStream is, String encoding) throws IOException
|
||||||
{
|
{
|
||||||
StringBuilder sb = new StringBuilder();
|
final StringBuilder sb = new StringBuilder();
|
||||||
InputStreamReader isr = new InputStreamReader(is, encoding);
|
final InputStreamReader isr = new InputStreamReader(is, encoding);
|
||||||
while (true) {
|
while (true) {
|
||||||
int temp = isr.read();
|
final int temp = isr.read();
|
||||||
if (temp < 0) {
|
if (temp < 0) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
char c = (char) temp;
|
final char c = (char) temp;
|
||||||
sb.append(c);
|
sb.append(c);
|
||||||
}
|
}
|
||||||
|
|
||||||
String read = sb.toString();
|
final String read = sb.toString();
|
||||||
|
|
||||||
String inputString = escapifyStr(read);
|
final String inputString = escapifyStr(read);
|
||||||
byte[] bs = inputString.getBytes("ISO-8859-1");
|
final byte[] bs = inputString.getBytes("ISO-8859-1");
|
||||||
ByteArrayInputStream bais = new ByteArrayInputStream(bs);
|
final ByteArrayInputStream bais = new ByteArrayInputStream(bs);
|
||||||
|
|
||||||
SortedProperties ps = props;
|
final SortedProperties ps = props;
|
||||||
ps.load(bais);
|
ps.load(bais);
|
||||||
return ps;
|
return ps;
|
||||||
}
|
}
|
||||||
@@ -491,7 +491,7 @@ public class PropertyManager {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
num = Integer.parseInt(string.trim());
|
num = Integer.parseInt(string.trim());
|
||||||
} catch (NumberFormatException e) {
|
} catch (final NumberFormatException e) {
|
||||||
num = defnum;
|
num = defnum;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -506,7 +506,7 @@ public class PropertyManager {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
num = Double.parseDouble(string.trim());
|
num = Double.parseDouble(string.trim());
|
||||||
} catch (NumberFormatException e) {
|
} catch (final NumberFormatException e) {
|
||||||
num = defnum;
|
num = defnum;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -529,7 +529,7 @@ public class PropertyManager {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
String string2 = string.toLowerCase();
|
final String string2 = string.toLowerCase();
|
||||||
bool = string2.equals("yes") || string2.equals("true") || string2.equals("on") || string2.equals("enabled") || string2.equals("enable");
|
bool = string2.equals("yes") || string2.equals("true") || string2.equals("on") || string2.equals("enabled") || string2.equals("enable");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -598,12 +598,12 @@ public class PropertyManager {
|
|||||||
/** Force save, even if nothing changed (used to save changed comments) */
|
/** Force save, even if nothing changed (used to save changed comments) */
|
||||||
private boolean cfgForceSave;
|
private boolean cfgForceSave;
|
||||||
|
|
||||||
private File file;
|
private final File file;
|
||||||
private String fileComment = "";
|
private String fileComment = "";
|
||||||
|
|
||||||
private TreeMap<String, Property> entries;
|
private final TreeMap<String, Property> entries;
|
||||||
private TreeMap<String, String> keyRename;
|
private final TreeMap<String, String> keyRename;
|
||||||
private TreeMap<String, String> setValues;
|
private final TreeMap<String, String> setValues;
|
||||||
private SortedProperties pr = new SortedProperties();
|
private SortedProperties pr = new SortedProperties();
|
||||||
|
|
||||||
|
|
||||||
@@ -634,13 +634,13 @@ public class PropertyManager {
|
|||||||
fis = new FileInputStream(file);
|
fis = new FileInputStream(file);
|
||||||
pr = PropertiesLoader.loadProperties(pr, fis);
|
pr = PropertiesLoader.loadProperties(pr, fis);
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
needsSave = true;
|
needsSave = true;
|
||||||
pr = new SortedProperties();
|
pr = new SortedProperties();
|
||||||
} finally {
|
} finally {
|
||||||
try {
|
try {
|
||||||
if (fis != null) fis.close();
|
if (fis != null) fis.close();
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -648,10 +648,10 @@ public class PropertyManager {
|
|||||||
pr.cfgSeparateSectionsByEmptyLine = cfgSeparateSections;
|
pr.cfgSeparateSectionsByEmptyLine = cfgSeparateSections;
|
||||||
pr.cfgEmptyLineBeforeComment = cfgNewlineBeforeComments;
|
pr.cfgEmptyLineBeforeComment = cfgNewlineBeforeComments;
|
||||||
|
|
||||||
ArrayList<String> keyList = new ArrayList<String>();
|
final ArrayList<String> keyList = new ArrayList<String>();
|
||||||
|
|
||||||
// rename keys
|
// rename keys
|
||||||
for (Entry<String, String> entry : keyRename.entrySet()) {
|
for (final Entry<String, String> entry : keyRename.entrySet()) {
|
||||||
if (pr.getProperty(entry.getKey()) == null) {
|
if (pr.getProperty(entry.getKey()) == null) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -661,16 +661,16 @@ public class PropertyManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// set the override values into the freshly loaded properties file
|
// set the override values into the freshly loaded properties file
|
||||||
for (Entry<String, String> entry : setValues.entrySet()) {
|
for (final Entry<String, String> entry : setValues.entrySet()) {
|
||||||
pr.setProperty(entry.getKey(), entry.getValue());
|
pr.setProperty(entry.getKey(), entry.getValue());
|
||||||
needsSave = true;
|
needsSave = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// validate entries one by one, replace with default when needed
|
// validate entries one by one, replace with default when needed
|
||||||
for (Property entry : entries.values()) {
|
for (final Property entry : entries.values()) {
|
||||||
keyList.add(entry.name);
|
keyList.add(entry.name);
|
||||||
|
|
||||||
String propOrig = pr.getProperty(entry.name);
|
final String propOrig = pr.getProperty(entry.name);
|
||||||
if (!entry.parse(propOrig)) needsSave = true;
|
if (!entry.parse(propOrig)) needsSave = true;
|
||||||
if (!cfgNoValidate) {
|
if (!cfgNoValidate) {
|
||||||
entry.validate();
|
entry.validate();
|
||||||
@@ -688,7 +688,7 @@ public class PropertyManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// removed unused props
|
// removed unused props
|
||||||
for (String propname : pr.keySet().toArray(new String[pr.size()])) {
|
for (final String propname : pr.keySet().toArray(new String[pr.size()])) {
|
||||||
if (!keyList.contains(propname)) {
|
if (!keyList.contains(propname)) {
|
||||||
pr.remove(propname);
|
pr.remove(propname);
|
||||||
needsSave = true;
|
needsSave = true;
|
||||||
@@ -700,7 +700,7 @@ public class PropertyManager {
|
|||||||
if (needsSave || cfgForceSave) {
|
if (needsSave || cfgForceSave) {
|
||||||
try {
|
try {
|
||||||
pr.store(new FileOutputStream(file), fileComment);
|
pr.store(new FileOutputStream(file), fileComment);
|
||||||
} catch (IOException ioe) {
|
} catch (final IOException ioe) {
|
||||||
ioe.printStackTrace();
|
ioe.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -756,7 +756,7 @@ public class PropertyManager {
|
|||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
return entries.get(n);
|
return entries.get(n);
|
||||||
} catch (Throwable t) {
|
} catch (final Throwable t) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -772,7 +772,7 @@ public class PropertyManager {
|
|||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
return entries.get(n).getBoolean();
|
return entries.get(n).getBoolean();
|
||||||
} catch (Throwable t) {
|
} catch (final Throwable t) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -788,7 +788,7 @@ public class PropertyManager {
|
|||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
return get(n).getInteger();
|
return get(n).getInteger();
|
||||||
} catch (Throwable t) {
|
} catch (final Throwable t) {
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -804,7 +804,7 @@ public class PropertyManager {
|
|||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
return get(n).getDouble();
|
return get(n).getDouble();
|
||||||
} catch (Throwable t) {
|
} catch (final Throwable t) {
|
||||||
return -1D;
|
return -1D;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -820,7 +820,7 @@ public class PropertyManager {
|
|||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
return get(n).getString();
|
return get(n).getString();
|
||||||
} catch (Throwable t) {
|
} catch (final Throwable t) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ public class SimpleConfig {
|
|||||||
*/
|
*/
|
||||||
public static List<String> listFromFile(File file) throws IOException
|
public static List<String> listFromFile(File file) throws IOException
|
||||||
{
|
{
|
||||||
String fileText = FileUtils.fileToString(file);
|
final String fileText = FileUtils.fileToString(file);
|
||||||
|
|
||||||
return listFromString(fileText);
|
return listFromString(fileText);
|
||||||
}
|
}
|
||||||
@@ -47,7 +47,7 @@ public class SimpleConfig {
|
|||||||
*/
|
*/
|
||||||
public static Map<String, String> mapFromFile(File file) throws IOException
|
public static Map<String, String> mapFromFile(File file) throws IOException
|
||||||
{
|
{
|
||||||
String fileText = FileUtils.fileToString(file);
|
final String fileText = FileUtils.fileToString(file);
|
||||||
|
|
||||||
return mapFromString(fileText);
|
return mapFromString(fileText);
|
||||||
}
|
}
|
||||||
@@ -61,9 +61,9 @@ public class SimpleConfig {
|
|||||||
*/
|
*/
|
||||||
public static List<String> listFromString(String text)
|
public static List<String> listFromString(String text)
|
||||||
{
|
{
|
||||||
List<String> list = new ArrayList<String>();
|
final List<String> list = new ArrayList<String>();
|
||||||
|
|
||||||
String[] groupsLines = text.split("\n");
|
final String[] groupsLines = text.split("\n");
|
||||||
|
|
||||||
for (String s : groupsLines) {
|
for (String s : groupsLines) {
|
||||||
// ignore invalid lines
|
// ignore invalid lines
|
||||||
@@ -91,11 +91,11 @@ public class SimpleConfig {
|
|||||||
*/
|
*/
|
||||||
public static Map<String, String> mapFromString(String text)
|
public static Map<String, String> mapFromString(String text)
|
||||||
{
|
{
|
||||||
LinkedHashMap<String, String> pairs = new LinkedHashMap<String, String>();
|
final LinkedHashMap<String, String> pairs = new LinkedHashMap<String, String>();
|
||||||
|
|
||||||
String[] groupsLines = text.split("\n");
|
final String[] groupsLines = text.split("\n");
|
||||||
|
|
||||||
for (String s : groupsLines) {
|
for (final String s : groupsLines) {
|
||||||
// ignore invalid lines
|
// ignore invalid lines
|
||||||
if (s.length() == 0) continue;
|
if (s.length() == 0) continue;
|
||||||
if (s.startsWith("#") || s.startsWith("//")) continue;
|
if (s.startsWith("#") || s.startsWith("//")) continue;
|
||||||
@@ -147,9 +147,9 @@ public class SimpleConfig {
|
|||||||
*/
|
*/
|
||||||
public static void mapToFile(File target, Map<String, String> data, boolean allowNulls) throws IOException
|
public static void mapToFile(File target, Map<String, String> data, boolean allowNulls) throws IOException
|
||||||
{
|
{
|
||||||
List<String> lines = new ArrayList<String>();
|
final List<String> lines = new ArrayList<String>();
|
||||||
|
|
||||||
for (Entry<String, String> e : data.entrySet()) {
|
for (final Entry<String, String> e : data.entrySet()) {
|
||||||
String key = e.getKey();
|
String key = e.getKey();
|
||||||
String value = e.getValue();
|
String value = e.getValue();
|
||||||
|
|
||||||
@@ -166,7 +166,7 @@ public class SimpleConfig {
|
|||||||
|
|
||||||
String text = ""; // # File written by SimpleConfig
|
String text = ""; // # File written by SimpleConfig
|
||||||
|
|
||||||
for (String s : lines) {
|
for (final String s : lines) {
|
||||||
if (text.length() > 0) text += "\n";
|
if (text.length() > 0) text += "\n";
|
||||||
|
|
||||||
text += s;
|
text += s;
|
||||||
|
|||||||
@@ -16,8 +16,8 @@ import mightypork.utils.logging.Log;
|
|||||||
*/
|
*/
|
||||||
public class ZipBuilder {
|
public class ZipBuilder {
|
||||||
|
|
||||||
private ZipOutputStream out;
|
private final ZipOutputStream out;
|
||||||
private HashSet<String> included = new HashSet<String>();
|
private final HashSet<String> included = new HashSet<String>();
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -28,7 +28,7 @@ public class ZipBuilder {
|
|||||||
public ZipBuilder(File target) throws FileNotFoundException {
|
public ZipBuilder(File target) throws FileNotFoundException {
|
||||||
target.getParentFile().mkdirs();
|
target.getParentFile().mkdirs();
|
||||||
|
|
||||||
FileOutputStream dest = new FileOutputStream(target);
|
final FileOutputStream dest = new FileOutputStream(target);
|
||||||
out = new ZipOutputStream(new BufferedOutputStream(dest));
|
out = new ZipOutputStream(new BufferedOutputStream(dest));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,7 +70,7 @@ public class ZipBuilder {
|
|||||||
|
|
||||||
out.putNextEntry(new ZipEntry(path));
|
out.putNextEntry(new ZipEntry(path));
|
||||||
|
|
||||||
InputStream in = FileUtils.stringToStream(text);
|
final InputStream in = FileUtils.stringToStream(text);
|
||||||
FileUtils.copyStream(in, out);
|
FileUtils.copyStream(in, out);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -90,7 +90,7 @@ public class ZipBuilder {
|
|||||||
|
|
||||||
out.putNextEntry(new ZipEntry(path));
|
out.putNextEntry(new ZipEntry(path));
|
||||||
|
|
||||||
InputStream in = FileUtils.getResource(resPath);
|
final InputStream in = FileUtils.getResource(resPath);
|
||||||
FileUtils.copyStream(in, out);
|
FileUtils.copyStream(in, out);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ public class ZipUtils {
|
|||||||
} finally {
|
} finally {
|
||||||
try {
|
try {
|
||||||
if (zip != null) zip.close();
|
if (zip != null) zip.close();
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
// ignore
|
// ignore
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -63,20 +63,20 @@ public class ZipUtils {
|
|||||||
*/
|
*/
|
||||||
public static List<String> extractZip(ZipFile zip, File outputDir, StringFilter filter) throws IOException
|
public static List<String> extractZip(ZipFile zip, File outputDir, StringFilter filter) throws IOException
|
||||||
{
|
{
|
||||||
ArrayList<String> files = new ArrayList<String>();
|
final ArrayList<String> files = new ArrayList<String>();
|
||||||
|
|
||||||
outputDir.mkdirs();
|
outputDir.mkdirs();
|
||||||
|
|
||||||
Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();
|
final Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();
|
||||||
|
|
||||||
// process each entry
|
// process each entry
|
||||||
while (zipFileEntries.hasMoreElements()) {
|
while (zipFileEntries.hasMoreElements()) {
|
||||||
ZipEntry entry = zipFileEntries.nextElement();
|
final ZipEntry entry = zipFileEntries.nextElement();
|
||||||
|
|
||||||
// parse filename and path
|
// parse filename and path
|
||||||
String entryPath = entry.getName();
|
final String entryPath = entry.getName();
|
||||||
File destFile = new File(outputDir, entryPath);
|
final File destFile = new File(outputDir, entryPath);
|
||||||
File destinationParent = destFile.getParentFile();
|
final File destinationParent = destFile.getParentFile();
|
||||||
|
|
||||||
if (entry.isDirectory() || (filter != null && !filter.accept(entryPath))) continue;
|
if (entry.isDirectory() || (filter != null && !filter.accept(entryPath))) continue;
|
||||||
|
|
||||||
@@ -109,7 +109,7 @@ public class ZipUtils {
|
|||||||
} finally {
|
} finally {
|
||||||
try {
|
try {
|
||||||
if (zip != null) zip.close();
|
if (zip != null) zip.close();
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
// ignore
|
// ignore
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -125,13 +125,13 @@ public class ZipUtils {
|
|||||||
*/
|
*/
|
||||||
public static List<String> listZip(ZipFile zip) throws IOException
|
public static List<String> listZip(ZipFile zip) throws IOException
|
||||||
{
|
{
|
||||||
ArrayList<String> files = new ArrayList<String>();
|
final ArrayList<String> files = new ArrayList<String>();
|
||||||
|
|
||||||
Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();
|
final Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();
|
||||||
|
|
||||||
// process each entry
|
// process each entry
|
||||||
while (zipFileEntries.hasMoreElements()) {
|
while (zipFileEntries.hasMoreElements()) {
|
||||||
ZipEntry entry = zipFileEntries.nextElement();
|
final ZipEntry entry = zipFileEntries.nextElement();
|
||||||
|
|
||||||
if (!entry.isDirectory()) {
|
if (!entry.isDirectory()) {
|
||||||
files.add(entry.getName());
|
files.add(entry.getName());
|
||||||
@@ -167,13 +167,13 @@ public class ZipUtils {
|
|||||||
} finally {
|
} finally {
|
||||||
try {
|
try {
|
||||||
if (is != null) is.close();
|
if (is != null) is.close();
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
// ignore
|
// ignore
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (dest != null) dest.close();
|
if (dest != null) dest.close();
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
// ignore
|
// ignore
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -194,12 +194,12 @@ public class ZipUtils {
|
|||||||
BufferedInputStream is = null;
|
BufferedInputStream is = null;
|
||||||
try {
|
try {
|
||||||
is = new BufferedInputStream(zip.getInputStream(entry));
|
is = new BufferedInputStream(zip.getInputStream(entry));
|
||||||
String s = FileUtils.streamToString(is);
|
final String s = FileUtils.streamToString(is);
|
||||||
return s;
|
return s;
|
||||||
} finally {
|
} finally {
|
||||||
try {
|
try {
|
||||||
if (is != null) is.close();
|
if (is != null) is.close();
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
// ignore
|
// ignore
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -213,12 +213,12 @@ public class ZipUtils {
|
|||||||
try {
|
try {
|
||||||
zf = new ZipFile(selectedFile);
|
zf = new ZipFile(selectedFile);
|
||||||
return zf.getEntry(string) != null;
|
return zf.getEntry(string) != null;
|
||||||
} catch (Exception e) {
|
} catch (final Exception e) {
|
||||||
return false;
|
return false;
|
||||||
} finally {
|
} finally {
|
||||||
try {
|
try {
|
||||||
if (zf != null) zf.close();
|
if (zf != null) zf.close();
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
// ignore
|
// ignore
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,10 +20,10 @@ public abstract class AbstractIonList<T> extends ArrayList<T> implements Ionizab
|
|||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
while (true) {
|
while (true) {
|
||||||
byte b = BinaryUtils.readByte(in);
|
final byte b = BinaryUtils.readByte(in);
|
||||||
|
|
||||||
if (b == IonMarks.ENTRY) {
|
if (b == IonMarks.ENTRY) {
|
||||||
T value = (T) Ion.readObject(in);
|
final T value = (T) Ion.readObject(in);
|
||||||
add(value);
|
add(value);
|
||||||
} else if (b == IonMarks.END) {
|
} else if (b == IonMarks.END) {
|
||||||
break;
|
break;
|
||||||
@@ -32,7 +32,7 @@ public abstract class AbstractIonList<T> extends ArrayList<T> implements Ionizab
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
ionReadCustomData(in);
|
ionReadCustomData(in);
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
throw new IonException("Error reading ion list", e);
|
throw new IonException("Error reading ion list", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -42,14 +42,14 @@ public abstract class AbstractIonList<T> extends ArrayList<T> implements Ionizab
|
|||||||
public void ionWrite(OutputStream out) throws IonException
|
public void ionWrite(OutputStream out) throws IonException
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
for (T entry : this) {
|
for (final T entry : this) {
|
||||||
if (entry instanceof IonizableOptional && !((IonizableOptional) entry).ionShouldSave()) continue;
|
if (entry instanceof IonizableOptional && !((IonizableOptional) entry).ionShouldSave()) continue;
|
||||||
BinaryUtils.writeByte(out, IonMarks.ENTRY);
|
BinaryUtils.writeByte(out, IonMarks.ENTRY);
|
||||||
Ion.writeObject(out, entry);
|
Ion.writeObject(out, entry);
|
||||||
}
|
}
|
||||||
BinaryUtils.writeByte(out, IonMarks.END);
|
BinaryUtils.writeByte(out, IonMarks.END);
|
||||||
ionWriteCustomData(out);
|
ionWriteCustomData(out);
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
throw new IonException("Error reading ion map", e);
|
throw new IonException("Error reading ion map", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,11 +34,11 @@ public abstract class AbstractIonMap<V> extends LinkedHashMap<String, V> impleme
|
|||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
while (true) {
|
while (true) {
|
||||||
byte b = BinaryUtils.readByte(in);
|
final byte b = BinaryUtils.readByte(in);
|
||||||
if (b == IonMarks.ENTRY) {
|
if (b == IonMarks.ENTRY) {
|
||||||
String key = BinaryUtils.readString(in);
|
final String key = BinaryUtils.readString(in);
|
||||||
|
|
||||||
V value = (V) Ion.readObject(in);
|
final V value = (V) Ion.readObject(in);
|
||||||
put(key, value);
|
put(key, value);
|
||||||
|
|
||||||
} else if (b == IonMarks.END) {
|
} else if (b == IonMarks.END) {
|
||||||
@@ -48,7 +48,7 @@ public abstract class AbstractIonMap<V> extends LinkedHashMap<String, V> impleme
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
ionReadCustomData(in);
|
ionReadCustomData(in);
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
throw new IonException("Error reading ion map", e);
|
throw new IonException("Error reading ion map", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -58,14 +58,14 @@ public abstract class AbstractIonMap<V> extends LinkedHashMap<String, V> impleme
|
|||||||
public void ionWrite(OutputStream out) throws IonException
|
public void ionWrite(OutputStream out) throws IonException
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
for (java.util.Map.Entry<String, V> entry : entrySet()) {
|
for (final java.util.Map.Entry<String, V> entry : entrySet()) {
|
||||||
BinaryUtils.writeByte(out, IonMarks.ENTRY);
|
BinaryUtils.writeByte(out, IonMarks.ENTRY);
|
||||||
BinaryUtils.writeString(out, entry.getKey());
|
BinaryUtils.writeString(out, entry.getKey());
|
||||||
Ion.writeObject(out, entry.getValue());
|
Ion.writeObject(out, entry.getValue());
|
||||||
}
|
}
|
||||||
BinaryUtils.writeByte(out, IonMarks.END);
|
BinaryUtils.writeByte(out, IonMarks.END);
|
||||||
ionWriteCustomData(out);
|
ionWriteCustomData(out);
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
throw new IonException("Error reading ion map", e);
|
throw new IonException("Error reading ion map", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -93,10 +93,10 @@ public class BinaryUtils {
|
|||||||
|
|
||||||
public static byte[] getBytesString(String str)
|
public static byte[] getBytesString(String str)
|
||||||
{
|
{
|
||||||
char[] chars = str.toCharArray();
|
final char[] chars = str.toCharArray();
|
||||||
|
|
||||||
ByteBuffer bstr = ByteBuffer.allocate((Character.SIZE / 8) * chars.length + (Character.SIZE / 8));
|
final ByteBuffer bstr = ByteBuffer.allocate((Character.SIZE / 8) * chars.length + (Character.SIZE / 8));
|
||||||
for (char c : chars) {
|
for (final char c : chars) {
|
||||||
bstr.putChar(c);
|
bstr.putChar(c);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -177,7 +177,7 @@ public class BinaryUtils {
|
|||||||
public static char readChar(InputStream in) throws IOException
|
public static char readChar(InputStream in) throws IOException
|
||||||
{
|
{
|
||||||
in.read(ac, 0, ac.length);
|
in.read(ac, 0, ac.length);
|
||||||
ByteBuffer buf = ByteBuffer.wrap(ac);
|
final ByteBuffer buf = ByteBuffer.wrap(ac);
|
||||||
return buf.getChar();
|
return buf.getChar();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,7 +185,7 @@ public class BinaryUtils {
|
|||||||
public static short readShort(InputStream in) throws IOException
|
public static short readShort(InputStream in) throws IOException
|
||||||
{
|
{
|
||||||
in.read(as, 0, as.length);
|
in.read(as, 0, as.length);
|
||||||
ByteBuffer buf = ByteBuffer.wrap(as);
|
final ByteBuffer buf = ByteBuffer.wrap(as);
|
||||||
return buf.getShort();
|
return buf.getShort();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -193,7 +193,7 @@ public class BinaryUtils {
|
|||||||
public static long readLong(InputStream in) throws IOException
|
public static long readLong(InputStream in) throws IOException
|
||||||
{
|
{
|
||||||
in.read(al, 0, al.length);
|
in.read(al, 0, al.length);
|
||||||
ByteBuffer buf = ByteBuffer.wrap(al);
|
final ByteBuffer buf = ByteBuffer.wrap(al);
|
||||||
return buf.getLong();
|
return buf.getLong();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -201,7 +201,7 @@ public class BinaryUtils {
|
|||||||
public static int readInt(InputStream in) throws IOException
|
public static int readInt(InputStream in) throws IOException
|
||||||
{
|
{
|
||||||
in.read(ai, 0, ai.length);
|
in.read(ai, 0, ai.length);
|
||||||
ByteBuffer buf = ByteBuffer.wrap(ai);
|
final ByteBuffer buf = ByteBuffer.wrap(ai);
|
||||||
return buf.getInt();
|
return buf.getInt();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -209,7 +209,7 @@ public class BinaryUtils {
|
|||||||
public static float readFloat(InputStream in) throws IOException
|
public static float readFloat(InputStream in) throws IOException
|
||||||
{
|
{
|
||||||
in.read(af, 0, af.length);
|
in.read(af, 0, af.length);
|
||||||
ByteBuffer buf = ByteBuffer.wrap(af);
|
final ByteBuffer buf = ByteBuffer.wrap(af);
|
||||||
return buf.getFloat();
|
return buf.getFloat();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -217,7 +217,7 @@ public class BinaryUtils {
|
|||||||
public static double readDouble(InputStream in) throws IOException
|
public static double readDouble(InputStream in) throws IOException
|
||||||
{
|
{
|
||||||
in.read(ad, 0, ad.length);
|
in.read(ad, 0, ad.length);
|
||||||
ByteBuffer buf = ByteBuffer.wrap(ad);
|
final ByteBuffer buf = ByteBuffer.wrap(ad);
|
||||||
return buf.getDouble();
|
return buf.getDouble();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ public class Ion {
|
|||||||
try {
|
try {
|
||||||
registerIonizable(IonMarks.MAP, IonMap.class);
|
registerIonizable(IonMarks.MAP, IonMap.class);
|
||||||
registerIonizable(IonMarks.LIST, IonList.class);
|
registerIonizable(IonMarks.LIST, IonList.class);
|
||||||
} catch (IonException e) {
|
} catch (final IonException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -70,16 +70,16 @@ public class Ion {
|
|||||||
InputStream in = null;
|
InputStream in = null;
|
||||||
try {
|
try {
|
||||||
in = new FileInputStream(file);
|
in = new FileInputStream(file);
|
||||||
Object obj = fromStream(in);
|
final Object obj = fromStream(in);
|
||||||
return obj;
|
return obj;
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
throw new IonException("Error loading ION file.", e);
|
throw new IonException("Error loading ION file.", e);
|
||||||
} finally {
|
} finally {
|
||||||
if (in != null) {
|
if (in != null) {
|
||||||
try {
|
try {
|
||||||
in.close();
|
in.close();
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -124,8 +124,8 @@ public class Ion {
|
|||||||
{
|
{
|
||||||
OutputStream out = null;
|
OutputStream out = null;
|
||||||
try {
|
try {
|
||||||
String f = path.toString();
|
final String f = path.toString();
|
||||||
File dir = new File(f.substring(0, f.lastIndexOf(File.separator)));
|
final File dir = new File(f.substring(0, f.lastIndexOf(File.separator)));
|
||||||
|
|
||||||
dir.mkdirs();
|
dir.mkdirs();
|
||||||
|
|
||||||
@@ -135,13 +135,13 @@ public class Ion {
|
|||||||
|
|
||||||
out.flush();
|
out.flush();
|
||||||
out.close();
|
out.close();
|
||||||
} catch (Exception e) {
|
} catch (final Exception e) {
|
||||||
throw new IonException("Error writing to ION file.", e);
|
throw new IonException("Error writing to ION file.", e);
|
||||||
} finally {
|
} finally {
|
||||||
if (out != null) {
|
if (out != null) {
|
||||||
try {
|
try {
|
||||||
out.close();
|
out.close();
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -173,16 +173,16 @@ public class Ion {
|
|||||||
public static Object readObject(InputStream in) throws IonException
|
public static Object readObject(InputStream in) throws IonException
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
int bi = in.read();
|
final int bi = in.read();
|
||||||
if (bi == -1) throw new IonException("Unexpected end of stream.");
|
if (bi == -1) throw new IonException("Unexpected end of stream.");
|
||||||
byte b = (byte) bi;
|
final byte b = (byte) bi;
|
||||||
if (customIonizables.containsKey(b)) {
|
if (customIonizables.containsKey(b)) {
|
||||||
Ionizable ion;
|
Ionizable ion;
|
||||||
try {
|
try {
|
||||||
ion = ((Ionizable) customIonizables.get(b).newInstance());
|
ion = ((Ionizable) customIonizables.get(b).newInstance());
|
||||||
} catch (InstantiationException e) {
|
} catch (final InstantiationException e) {
|
||||||
throw new IonException("Cound not instantiate " + customIonizables.get(b).getSimpleName(), e);
|
throw new IonException("Cound not instantiate " + customIonizables.get(b).getSimpleName(), e);
|
||||||
} catch (IllegalAccessException e) {
|
} catch (final IllegalAccessException e) {
|
||||||
throw new IonException("Cound not instantiate " + customIonizables.get(b).getSimpleName(), e);
|
throw new IonException("Cound not instantiate " + customIonizables.get(b).getSimpleName(), e);
|
||||||
}
|
}
|
||||||
ion.ionRead(in);
|
ion.ionRead(in);
|
||||||
@@ -207,12 +207,12 @@ public class Ion {
|
|||||||
case IonMarks.DOUBLE:
|
case IonMarks.DOUBLE:
|
||||||
return BinaryUtils.readDouble(in);
|
return BinaryUtils.readDouble(in);
|
||||||
case IonMarks.STRING:
|
case IonMarks.STRING:
|
||||||
String s = BinaryUtils.readString(in);
|
final String s = BinaryUtils.readString(in);
|
||||||
return s;
|
return s;
|
||||||
default:
|
default:
|
||||||
throw new IonException("Invalid Ion mark " + Integer.toHexString(bi));
|
throw new IonException("Invalid Ion mark " + Integer.toHexString(bi));
|
||||||
}
|
}
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
throw new IonException("Error loading ION file: ", e);
|
throw new IonException("Error loading ION file: ", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -290,7 +290,7 @@ public class Ion {
|
|||||||
|
|
||||||
throw new IonException(Calc.cname(obj) + " can't be stored in Ion storage.");
|
throw new IonException(Calc.cname(obj) + " can't be stored in Ion storage.");
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
throw new IonException("Could not store " + obj, e);
|
throw new IonException("Could not store " + obj, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -131,12 +131,12 @@ public class IonList extends AbstractIonList<Object> {
|
|||||||
public Object getCheckType(int index, Class<?> type) throws IonException
|
public Object getCheckType(int index, Class<?> type) throws IonException
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
Object o = super.get(index);
|
final Object o = super.get(index);
|
||||||
if (o == null || !o.getClass().isAssignableFrom(type)) {
|
if (o == null || !o.getClass().isAssignableFrom(type)) {
|
||||||
throw new IonException("Incorrect object type");
|
throw new IonException("Incorrect object type");
|
||||||
}
|
}
|
||||||
return o;
|
return o;
|
||||||
} catch (IndexOutOfBoundsException e) {
|
} catch (final IndexOutOfBoundsException e) {
|
||||||
throw new IonException("Out of bounds");
|
throw new IonException("Out of bounds");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -133,7 +133,7 @@ public class Log {
|
|||||||
public static synchronized LogInstance create(String logName, File logsDir, int oldLogsCount)
|
public static synchronized LogInstance create(String logName, File logsDir, int oldLogsCount)
|
||||||
{
|
{
|
||||||
if (logs.containsKey(logName)) return logs.get(logName);
|
if (logs.containsKey(logName)) return logs.get(logName);
|
||||||
LogInstance log = new LogInstance(logName, logsDir, oldLogsCount);
|
final LogInstance log = new LogInstance(logName, logsDir, oldLogsCount);
|
||||||
if (main == null) main = log;
|
if (main == null) main = log;
|
||||||
logs.put(logName, log);
|
logs.put(logName, log);
|
||||||
|
|
||||||
@@ -153,7 +153,7 @@ public class Log {
|
|||||||
public static synchronized LogInstance create(String logName, File logsDir)
|
public static synchronized LogInstance create(String logName, File logsDir)
|
||||||
{
|
{
|
||||||
if (logs.containsKey(logName)) return logs.get(logName);
|
if (logs.containsKey(logName)) return logs.get(logName);
|
||||||
LogInstance log = new LogInstance(logName, logsDir, -1);
|
final LogInstance log = new LogInstance(logName, logsDir, -1);
|
||||||
if (main == null) main = log;
|
if (main == null) main = log;
|
||||||
logs.put(logName, log);
|
logs.put(logName, log);
|
||||||
|
|
||||||
@@ -184,7 +184,7 @@ public class Log {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
hasToString = (o.getClass().getMethod("toString").getDeclaringClass() != Object.class);
|
hasToString = (o.getClass().getMethod("toString").getDeclaringClass() != Object.class);
|
||||||
} catch (Exception e) {
|
} catch (final Exception e) {
|
||||||
// oh well..
|
// oh well..
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -192,9 +192,9 @@ public class Log {
|
|||||||
return o.toString();
|
return o.toString();
|
||||||
} else {
|
} else {
|
||||||
|
|
||||||
Class<?> cls = o.getClass();
|
final Class<?> cls = o.getClass();
|
||||||
|
|
||||||
Class<?> enclosing = cls.getEnclosingClass();
|
final Class<?> enclosing = cls.getEnclosingClass();
|
||||||
|
|
||||||
return (enclosing == null ? "" : enclosing.getSimpleName() + ".") + cls.getSimpleName();
|
return (enclosing == null ? "" : enclosing.getSimpleName() + ".") + cls.getSimpleName();
|
||||||
}
|
}
|
||||||
@@ -203,7 +203,7 @@ public class Log {
|
|||||||
|
|
||||||
public static String str(Class<?> cls)
|
public static String str(Class<?> cls)
|
||||||
{
|
{
|
||||||
Class<?> enclosing = cls.getEnclosingClass();
|
final Class<?> enclosing = cls.getEnclosingClass();
|
||||||
|
|
||||||
return (enclosing == null ? "" : enclosing.getSimpleName() + ".") + cls.getSimpleName();
|
return (enclosing == null ? "" : enclosing.getSimpleName() + ".") + cls.getSimpleName();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,16 +29,16 @@ import mightypork.utils.files.FileUtils;
|
|||||||
public class LogInstance {
|
public class LogInstance {
|
||||||
|
|
||||||
/** log file */
|
/** log file */
|
||||||
private File file;
|
private final File file;
|
||||||
|
|
||||||
/** Log name */
|
/** Log name */
|
||||||
private String name;
|
private final String name;
|
||||||
|
|
||||||
/** Number of old logs to keep */
|
/** Number of old logs to keep */
|
||||||
private int logs_to_keep;
|
private final int logs_to_keep;
|
||||||
|
|
||||||
/** Logs dir */
|
/** Logs dir */
|
||||||
private File dir;
|
private final File dir;
|
||||||
|
|
||||||
/** Logger instance. */
|
/** Logger instance. */
|
||||||
private Logger logger;
|
private Logger logger;
|
||||||
@@ -49,7 +49,7 @@ public class LogInstance {
|
|||||||
private boolean sysout = true;
|
private boolean sysout = true;
|
||||||
|
|
||||||
private int monitorId = 0;
|
private int monitorId = 0;
|
||||||
private HashMap<Integer, LogMonitor> monitors = new HashMap<Integer, LogMonitor>();
|
private final HashMap<Integer, LogMonitor> monitors = new HashMap<Integer, LogMonitor>();
|
||||||
|
|
||||||
private LogToSysoutMonitor sysoutMonitor;
|
private LogToSysoutMonitor sysoutMonitor;
|
||||||
|
|
||||||
@@ -77,7 +77,7 @@ public class LogInstance {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
handler = new FileHandler(file.getPath());
|
handler = new FileHandler(file.getPath());
|
||||||
} catch (Exception e) {
|
} catch (final Exception e) {
|
||||||
throw new RuntimeException("Failed to init log", e);
|
throw new RuntimeException("Failed to init log", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,13 +101,13 @@ public class LogInstance {
|
|||||||
{
|
{
|
||||||
if (logs_to_keep == 0) return; // overwrite
|
if (logs_to_keep == 0) return; // overwrite
|
||||||
|
|
||||||
for (File f : FileUtils.listDirectory(file.getParentFile())) {
|
for (final File f : FileUtils.listDirectory(file.getParentFile())) {
|
||||||
if (!f.isFile()) continue;
|
if (!f.isFile()) continue;
|
||||||
if (f.equals(file)) {
|
if (f.equals(file)) {
|
||||||
Date d = new Date(f.lastModified());
|
final Date d = new Date(f.lastModified());
|
||||||
|
|
||||||
String fbase = name + '_' + (new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss")).format(d);
|
final String fbase = name + '_' + (new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss")).format(d);
|
||||||
String suff = getSuffix();
|
final String suff = getSuffix();
|
||||||
String cntStr = "";
|
String cntStr = "";
|
||||||
File f2;
|
File f2;
|
||||||
|
|
||||||
@@ -119,7 +119,7 @@ public class LogInstance {
|
|||||||
|
|
||||||
if (logs_to_keep == -1) return; // keep all
|
if (logs_to_keep == -1) return; // keep all
|
||||||
|
|
||||||
List<File> oldLogs = FileUtils.listDirectory(dir, new FileFilter() {
|
final List<File> oldLogs = FileUtils.listDirectory(dir, new FileFilter() {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean accept(File f)
|
public boolean accept(File f)
|
||||||
@@ -156,7 +156,7 @@ public class LogInstance {
|
|||||||
*/
|
*/
|
||||||
public synchronized int addMonitor(LogMonitor mon)
|
public synchronized int addMonitor(LogMonitor mon)
|
||||||
{
|
{
|
||||||
int id = monitorId;
|
final int id = monitorId;
|
||||||
monitorId++;
|
monitorId++;
|
||||||
monitors.put(id, mon);
|
monitors.put(id, mon);
|
||||||
return id;
|
return id;
|
||||||
@@ -294,8 +294,8 @@ public class LogInstance {
|
|||||||
*/
|
*/
|
||||||
private static String getStackTrace(Throwable t)
|
private static String getStackTrace(Throwable t)
|
||||||
{
|
{
|
||||||
StringWriter sw = new StringWriter();
|
final StringWriter sw = new StringWriter();
|
||||||
PrintWriter pw = new PrintWriter(sw, true);
|
final PrintWriter pw = new PrintWriter(sw, true);
|
||||||
t.printStackTrace(pw);
|
t.printStackTrace(pw);
|
||||||
pw.flush();
|
pw.flush();
|
||||||
sw.flush();
|
sw.flush();
|
||||||
@@ -317,7 +317,7 @@ public class LogInstance {
|
|||||||
@Override
|
@Override
|
||||||
public String format(LogRecord record)
|
public String format(LogRecord record)
|
||||||
{
|
{
|
||||||
StringBuffer buf = new StringBuffer(180);
|
final StringBuffer buf = new StringBuffer(180);
|
||||||
|
|
||||||
if (record.getMessage().equals("\n")) {
|
if (record.getMessage().equals("\n")) {
|
||||||
return nl;
|
return nl;
|
||||||
@@ -328,7 +328,7 @@ public class LogInstance {
|
|||||||
record.setMessage(record.getMessage().substring(1));
|
record.setMessage(record.getMessage().substring(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
Level level = record.getLevel();
|
final Level level = record.getLevel();
|
||||||
String trail = "[ ? ]";
|
String trail = "[ ? ]";
|
||||||
if (level == Level.FINE) {
|
if (level == Level.FINE) {
|
||||||
trail = "[ # ] ";
|
trail = "[ # ] ";
|
||||||
@@ -356,7 +356,7 @@ public class LogInstance {
|
|||||||
|
|
||||||
buf.append(nl);
|
buf.append(nl);
|
||||||
|
|
||||||
Throwable throwable = record.getThrown();
|
final Throwable throwable = record.getThrown();
|
||||||
if (throwable != null) {
|
if (throwable != null) {
|
||||||
buf.append("at ");
|
buf.append("at ");
|
||||||
buf.append(record.getSourceClassName());
|
buf.append(record.getSourceClassName());
|
||||||
@@ -364,16 +364,16 @@ public class LogInstance {
|
|||||||
buf.append(record.getSourceMethodName());
|
buf.append(record.getSourceMethodName());
|
||||||
buf.append(nl);
|
buf.append(nl);
|
||||||
|
|
||||||
StringWriter sink = new StringWriter();
|
final StringWriter sink = new StringWriter();
|
||||||
throwable.printStackTrace(new PrintWriter(sink, true));
|
throwable.printStackTrace(new PrintWriter(sink, true));
|
||||||
buf.append(sink.toString());
|
buf.append(sink.toString());
|
||||||
|
|
||||||
buf.append(nl);
|
buf.append(nl);
|
||||||
}
|
}
|
||||||
|
|
||||||
String str = buf.toString();
|
final String str = buf.toString();
|
||||||
|
|
||||||
for (LogMonitor mon : monitors.values()) {
|
for (final LogMonitor mon : monitors.values()) {
|
||||||
mon.log(level, str);
|
mon.log(level, str);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -34,17 +34,17 @@ public class Calc {
|
|||||||
public static double linePointDist(Coord lineDirVec, Coord linePoint, Coord point)
|
public static double linePointDist(Coord lineDirVec, Coord linePoint, Coord point)
|
||||||
{
|
{
|
||||||
// line point L[lx,ly]
|
// line point L[lx,ly]
|
||||||
double lx = linePoint.x;
|
final double lx = linePoint.x;
|
||||||
double ly = linePoint.y;
|
final double ly = linePoint.y;
|
||||||
|
|
||||||
// line equation ax+by+c=0
|
// line equation ax+by+c=0
|
||||||
double a = -lineDirVec.y;
|
final double a = -lineDirVec.y;
|
||||||
double b = lineDirVec.x;
|
final double b = lineDirVec.x;
|
||||||
double c = -a * lx - b * ly;
|
final double c = -a * lx - b * ly;
|
||||||
|
|
||||||
// checked point P[x,y]
|
// checked point P[x,y]
|
||||||
double x = point.x;
|
final double x = point.x;
|
||||||
double y = point.y;
|
final double y = point.y;
|
||||||
|
|
||||||
// distance
|
// distance
|
||||||
return Math.abs(a * x + b * y + c) / Math.sqrt(a * a + b * b);
|
return Math.abs(a * x + b * y + c) / Math.sqrt(a * a + b * b);
|
||||||
@@ -285,10 +285,10 @@ public class Calc {
|
|||||||
*/
|
*/
|
||||||
public static int roundX(double deg, double x)
|
public static int roundX(double deg, double x)
|
||||||
{
|
{
|
||||||
double half = x / 2d;
|
final double half = x / 2d;
|
||||||
deg += half;
|
deg += half;
|
||||||
deg = norm(deg);
|
deg = norm(deg);
|
||||||
int times = (int) Math.floor(deg / x);
|
final int times = (int) Math.floor(deg / x);
|
||||||
double a = times * x;
|
double a = times * x;
|
||||||
if (a == 360) a = 0;
|
if (a == 360) a = 0;
|
||||||
return (int) Math.round(a);
|
return (int) Math.round(a);
|
||||||
@@ -511,8 +511,8 @@ public class Calc {
|
|||||||
private static double clamp_double(Number number, Number min, Number max)
|
private static double clamp_double(Number number, Number min, Number max)
|
||||||
{
|
{
|
||||||
double n = number.doubleValue();
|
double n = number.doubleValue();
|
||||||
double mind = min.doubleValue();
|
final double mind = min.doubleValue();
|
||||||
double maxd = max.doubleValue();
|
final double maxd = max.doubleValue();
|
||||||
if (n > maxd) n = maxd;
|
if (n > maxd) n = maxd;
|
||||||
if (n < mind) n = mind;
|
if (n < mind) n = mind;
|
||||||
if (Double.isNaN(n)) return mind;
|
if (Double.isNaN(n)) return mind;
|
||||||
@@ -530,7 +530,7 @@ public class Calc {
|
|||||||
private static double clamp_double(Number number, Number min)
|
private static double clamp_double(Number number, Number min)
|
||||||
{
|
{
|
||||||
double n = number.doubleValue();
|
double n = number.doubleValue();
|
||||||
double mind = min.doubleValue();
|
final double mind = min.doubleValue();
|
||||||
if (n < mind) n = mind;
|
if (n < mind) n = mind;
|
||||||
return n;
|
return n;
|
||||||
}
|
}
|
||||||
@@ -790,7 +790,7 @@ public class Calc {
|
|||||||
public static double max(double... numbers)
|
public static double max(double... numbers)
|
||||||
{
|
{
|
||||||
double highest = numbers[0];
|
double highest = numbers[0];
|
||||||
for (double num : numbers) {
|
for (final double num : numbers) {
|
||||||
if (num > highest) highest = num;
|
if (num > highest) highest = num;
|
||||||
}
|
}
|
||||||
return highest;
|
return highest;
|
||||||
@@ -806,7 +806,7 @@ public class Calc {
|
|||||||
public static float max(float... numbers)
|
public static float max(float... numbers)
|
||||||
{
|
{
|
||||||
float highest = numbers[0];
|
float highest = numbers[0];
|
||||||
for (float num : numbers) {
|
for (final float num : numbers) {
|
||||||
if (num > highest) highest = num;
|
if (num > highest) highest = num;
|
||||||
}
|
}
|
||||||
return highest;
|
return highest;
|
||||||
@@ -822,7 +822,7 @@ public class Calc {
|
|||||||
public static int max(int... numbers)
|
public static int max(int... numbers)
|
||||||
{
|
{
|
||||||
int highest = numbers[0];
|
int highest = numbers[0];
|
||||||
for (int num : numbers) {
|
for (final int num : numbers) {
|
||||||
if (num > highest) highest = num;
|
if (num > highest) highest = num;
|
||||||
}
|
}
|
||||||
return highest;
|
return highest;
|
||||||
@@ -838,7 +838,7 @@ public class Calc {
|
|||||||
public static double min(double... numbers)
|
public static double min(double... numbers)
|
||||||
{
|
{
|
||||||
double lowest = numbers[0];
|
double lowest = numbers[0];
|
||||||
for (double num : numbers) {
|
for (final double num : numbers) {
|
||||||
if (num < lowest) lowest = num;
|
if (num < lowest) lowest = num;
|
||||||
}
|
}
|
||||||
return lowest;
|
return lowest;
|
||||||
@@ -854,7 +854,7 @@ public class Calc {
|
|||||||
public static float min(float... numbers)
|
public static float min(float... numbers)
|
||||||
{
|
{
|
||||||
float lowest = numbers[0];
|
float lowest = numbers[0];
|
||||||
for (float num : numbers) {
|
for (final float num : numbers) {
|
||||||
if (num < lowest) lowest = num;
|
if (num < lowest) lowest = num;
|
||||||
}
|
}
|
||||||
return lowest;
|
return lowest;
|
||||||
@@ -870,7 +870,7 @@ public class Calc {
|
|||||||
public static int min(int... numbers)
|
public static int min(int... numbers)
|
||||||
{
|
{
|
||||||
int lowest = numbers[0];
|
int lowest = numbers[0];
|
||||||
for (int num : numbers) {
|
for (final int num : numbers) {
|
||||||
if (num < lowest) lowest = num;
|
if (num < lowest) lowest = num;
|
||||||
}
|
}
|
||||||
return lowest;
|
return lowest;
|
||||||
@@ -888,14 +888,14 @@ public class Calc {
|
|||||||
if (list == null) {
|
if (list == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
String[] parts = list.split(",");
|
final String[] parts = list.split(",");
|
||||||
|
|
||||||
ArrayList<Integer> intList = new ArrayList<Integer>();
|
final ArrayList<Integer> intList = new ArrayList<Integer>();
|
||||||
|
|
||||||
for (String part : parts) {
|
for (final String part : parts) {
|
||||||
try {
|
try {
|
||||||
intList.add(Integer.parseInt(part));
|
intList.add(Integer.parseInt(part));
|
||||||
} catch (NumberFormatException e) {}
|
} catch (final NumberFormatException e) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
return intList;
|
return intList;
|
||||||
|
|||||||
@@ -161,7 +161,7 @@ public class Polar {
|
|||||||
if (this == obj) return true;
|
if (this == obj) return true;
|
||||||
if (obj == null) return false;
|
if (obj == null) return false;
|
||||||
if (!(obj instanceof Polar)) return false;
|
if (!(obj instanceof Polar)) return false;
|
||||||
Polar other = (Polar) obj;
|
final Polar other = (Polar) obj;
|
||||||
if (Double.doubleToLongBits(angle) != Double.doubleToLongBits(other.angle)) return false;
|
if (Double.doubleToLongBits(angle) != Double.doubleToLongBits(other.angle)) return false;
|
||||||
if (Double.doubleToLongBits(radius) != Double.doubleToLongBits(other.radius)) return false;
|
if (Double.doubleToLongBits(radius) != Double.doubleToLongBits(other.radius)) return false;
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ public class Range {
|
|||||||
*/
|
*/
|
||||||
public Range(double min, double max) {
|
public Range(double min, double max) {
|
||||||
if (min > max) {
|
if (min > max) {
|
||||||
double t = min;
|
final double t = min;
|
||||||
min = max;
|
min = max;
|
||||||
max = t;
|
max = t;
|
||||||
}
|
}
|
||||||
@@ -170,7 +170,7 @@ public class Range {
|
|||||||
max = other.max;
|
max = other.max;
|
||||||
|
|
||||||
if (min > max) {
|
if (min > max) {
|
||||||
double t = min;
|
final double t = min;
|
||||||
min = max;
|
min = max;
|
||||||
max = t;
|
max = t;
|
||||||
}
|
}
|
||||||
@@ -186,7 +186,7 @@ public class Range {
|
|||||||
public void setTo(double min, double max)
|
public void setTo(double min, double max)
|
||||||
{
|
{
|
||||||
if (min > max) {
|
if (min > max) {
|
||||||
double t = min;
|
final double t = min;
|
||||||
min = max;
|
min = max;
|
||||||
max = t;
|
max = t;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -191,12 +191,12 @@ public class AnimDouble implements Updateable, Pauseable {
|
|||||||
*/
|
*/
|
||||||
public void animate(double from, double to, double time)
|
public void animate(double from, double to, double time)
|
||||||
{
|
{
|
||||||
double current = now();
|
final double current = now();
|
||||||
|
|
||||||
this.from = from;
|
this.from = from;
|
||||||
this.to = to;
|
this.to = to;
|
||||||
|
|
||||||
double progress = getProgressFromValue(current);
|
final double progress = getProgressFromValue(current);
|
||||||
|
|
||||||
this.from = (progress > 0 ? current : from);
|
this.from = (progress > 0 ? current : from);
|
||||||
|
|
||||||
|
|||||||
@@ -38,9 +38,9 @@ public class AnimDoubleDeg extends AnimDouble {
|
|||||||
@Override
|
@Override
|
||||||
protected double getProgressFromValue(double value)
|
protected double getProgressFromValue(double value)
|
||||||
{
|
{
|
||||||
double whole = Deg.diff(from, to);
|
final double whole = Deg.diff(from, to);
|
||||||
if (Deg.diff(value, from) < whole && Deg.diff(value, to) < whole) {
|
if (Deg.diff(value, from) < whole && Deg.diff(value, to) < whole) {
|
||||||
double partial = Deg.diff(from, value);
|
final double partial = Deg.diff(from, value);
|
||||||
return partial / whole;
|
return partial / whole;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -38,9 +38,9 @@ public class AnimDoubleRad extends AnimDouble {
|
|||||||
@Override
|
@Override
|
||||||
protected double getProgressFromValue(double value)
|
protected double getProgressFromValue(double value)
|
||||||
{
|
{
|
||||||
double whole = Rad.diff(from, to);
|
final double whole = Rad.diff(from, to);
|
||||||
if (Rad.diff(value, from) < whole && Rad.diff(value, to) < whole) {
|
if (Rad.diff(value, from) < whole && Rad.diff(value, to) < whole) {
|
||||||
double partial = Rad.diff(from, value);
|
final double partial = Rad.diff(from, value);
|
||||||
return partial / whole;
|
return partial / whole;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ public abstract class Easing {
|
|||||||
*/
|
*/
|
||||||
private static class Reverse extends Easing {
|
private static class Reverse extends Easing {
|
||||||
|
|
||||||
private Easing ea;
|
private final Easing ea;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -85,8 +85,8 @@ public abstract class Easing {
|
|||||||
*/
|
*/
|
||||||
private static class Composite extends Easing {
|
private static class Composite extends Easing {
|
||||||
|
|
||||||
private Easing in;
|
private final Easing in;
|
||||||
private Easing out;
|
private final Easing out;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -277,7 +277,7 @@ public abstract class Easing {
|
|||||||
@Override
|
@Override
|
||||||
public double get(double t)
|
public double get(double t)
|
||||||
{
|
{
|
||||||
float s = 1.70158f;
|
final float s = 1.70158f;
|
||||||
return t * t * ((s + 1) * t - s);
|
return t * t * ((s + 1) * t - s);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -297,8 +297,8 @@ public abstract class Easing {
|
|||||||
if (t == 0) return 0;
|
if (t == 0) return 0;
|
||||||
if (t == 1) return 1;
|
if (t == 1) return 1;
|
||||||
|
|
||||||
double p = .3f;
|
final double p = .3f;
|
||||||
double s = p / 4;
|
final double s = p / 4;
|
||||||
return -(Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
|
return -(Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -125,7 +125,7 @@ public class HSV {
|
|||||||
{
|
{
|
||||||
norm();
|
norm();
|
||||||
|
|
||||||
int rgb = Color.HSBtoRGB((float) h, (float) s, (float) v);
|
final int rgb = Color.HSBtoRGB((float) h, (float) s, (float) v);
|
||||||
|
|
||||||
return RGB.fromHex(rgb);
|
return RGB.fromHex(rgb);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -311,9 +311,9 @@ public class RGB {
|
|||||||
*/
|
*/
|
||||||
public int getHex()
|
public int getHex()
|
||||||
{
|
{
|
||||||
int ri = (int) Math.round(r * 255);
|
final int ri = (int) Math.round(r * 255);
|
||||||
int gi = (int) Math.round(g * 255);
|
final int gi = (int) Math.round(g * 255);
|
||||||
int bi = (int) Math.round(b * 255);
|
final int bi = (int) Math.round(b * 255);
|
||||||
return (ri << 16) | (gi << 8) | bi;
|
return (ri << 16) | (gi << 8) | bi;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -325,7 +325,7 @@ public class RGB {
|
|||||||
*/
|
*/
|
||||||
public HSV toHSV()
|
public HSV toHSV()
|
||||||
{
|
{
|
||||||
float[] hsv = { 0, 0, 0 };
|
final float[] hsv = { 0, 0, 0 };
|
||||||
Color.RGBtoHSB((int) (r * 255), (int) (g * 255), (int) (b * 255), hsv);
|
Color.RGBtoHSB((int) (r * 255), (int) (g * 255), (int) (b * 255), hsv);
|
||||||
return new HSV(hsv[0], hsv[1], hsv[2]);
|
return new HSV(hsv[0], hsv[1], hsv[2]);
|
||||||
}
|
}
|
||||||
@@ -339,9 +339,9 @@ public class RGB {
|
|||||||
*/
|
*/
|
||||||
public static RGB fromHex(int hex)
|
public static RGB fromHex(int hex)
|
||||||
{
|
{
|
||||||
int bi = hex & 0xff;
|
final int bi = hex & 0xff;
|
||||||
int gi = (hex >> 8) & 0xff;
|
final int gi = (hex >> 8) & 0xff;
|
||||||
int ri = (hex >> 16) & 0xff;
|
final int ri = (hex >> 16) & 0xff;
|
||||||
return new RGB(ri / 255D, gi / 255D, bi / 255D);
|
return new RGB(ri / 255D, gi / 255D, bi / 255D);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -242,8 +242,8 @@ public class ConstraintFactory {
|
|||||||
@Override
|
@Override
|
||||||
public Rect getRect()
|
public Rect getRect()
|
||||||
{
|
{
|
||||||
double height = getContext().getRect().size().y;
|
final double height = getContext().getRect().size().y;
|
||||||
double perRow = height / rows;
|
final double perRow = height / rows;
|
||||||
|
|
||||||
return Rect.fromSize(getOrigin().add(0, perRow * index), getSize().setY(perRow));
|
return Rect.fromSize(getOrigin().add(0, perRow * index), getSize().setY(perRow));
|
||||||
}
|
}
|
||||||
@@ -258,8 +258,8 @@ public class ConstraintFactory {
|
|||||||
@Override
|
@Override
|
||||||
public Rect getRect()
|
public Rect getRect()
|
||||||
{
|
{
|
||||||
double width = getContext().getRect().size().x;
|
final double width = getContext().getRect().size().x;
|
||||||
double perCol = width / columns;
|
final double perCol = width / columns;
|
||||||
|
|
||||||
return Rect.fromSize(getOrigin().add(perCol * index, 0), getSize().setX(perCol));
|
return Rect.fromSize(getOrigin().add(perCol * index, 0), getSize().setX(perCol));
|
||||||
}
|
}
|
||||||
@@ -337,10 +337,10 @@ public class ConstraintFactory {
|
|||||||
@Override
|
@Override
|
||||||
public Rect getRect()
|
public Rect getRect()
|
||||||
{
|
{
|
||||||
double height = getSize().y;
|
final double height = getSize().y;
|
||||||
double width = getSize().y;
|
final double width = getSize().y;
|
||||||
double perRow = height / rows;
|
final double perRow = height / rows;
|
||||||
double perCol = width / cols;
|
final double perCol = width / cols;
|
||||||
|
|
||||||
return Rect.fromSize(getOrigin().add(perCol * left, perRow * (rows - top - 1)), perCol, perRow);
|
return Rect.fromSize(getOrigin().add(perCol * left, perRow * (rows - top - 1)), perCol, perRow);
|
||||||
}
|
}
|
||||||
@@ -355,7 +355,7 @@ public class ConstraintFactory {
|
|||||||
@Override
|
@Override
|
||||||
public Rect getRect()
|
public Rect getRect()
|
||||||
{
|
{
|
||||||
Coord origin = getOrigin();
|
final Coord origin = getOrigin();
|
||||||
|
|
||||||
//@formatter:off
|
//@formatter:off
|
||||||
return Rect.fromSize(
|
return Rect.fromSize(
|
||||||
@@ -377,7 +377,7 @@ public class ConstraintFactory {
|
|||||||
@Override
|
@Override
|
||||||
public Rect getRect()
|
public Rect getRect()
|
||||||
{
|
{
|
||||||
Coord origin = getOrigin();
|
final Coord origin = getOrigin();
|
||||||
|
|
||||||
//@formatter:off
|
//@formatter:off
|
||||||
return Rect.fromSize(
|
return Rect.fromSize(
|
||||||
@@ -399,7 +399,7 @@ public class ConstraintFactory {
|
|||||||
@Override
|
@Override
|
||||||
public Rect getRect()
|
public Rect getRect()
|
||||||
{
|
{
|
||||||
Coord origin = getOrigin();
|
final Coord origin = getOrigin();
|
||||||
|
|
||||||
//@formatter:off
|
//@formatter:off
|
||||||
return new Rect(
|
return new Rect(
|
||||||
|
|||||||
@@ -863,7 +863,7 @@ public class Coord {
|
|||||||
{
|
{
|
||||||
if (isZero()) return this;
|
if (isZero()) return this;
|
||||||
|
|
||||||
double k = size / size();
|
final double k = size / size();
|
||||||
return mul_ip(k);
|
return mul_ip(k);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -919,7 +919,7 @@ public class Coord {
|
|||||||
if (this == obj) return true;
|
if (this == obj) return true;
|
||||||
if (obj == null) return false;
|
if (obj == null) return false;
|
||||||
if (!(obj instanceof Coord)) return false;
|
if (!(obj instanceof Coord)) return false;
|
||||||
Coord other = (Coord) obj;
|
final Coord other = (Coord) obj;
|
||||||
if (Double.doubleToLongBits(x) != Double.doubleToLongBits(other.x)) return false;
|
if (Double.doubleToLongBits(x) != Double.doubleToLongBits(other.x)) return false;
|
||||||
if (Double.doubleToLongBits(y) != Double.doubleToLongBits(other.y)) return false;
|
if (Double.doubleToLongBits(y) != Double.doubleToLongBits(other.y)) return false;
|
||||||
if (Double.doubleToLongBits(z) != Double.doubleToLongBits(other.z)) return false;
|
if (Double.doubleToLongBits(z) != Double.doubleToLongBits(other.z)) return false;
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ public class Convertor {
|
|||||||
if (o instanceof Number) return ((Number) o).intValue();
|
if (o instanceof Number) return ((Number) o).intValue();
|
||||||
if (o instanceof Range) return ((Range) o).randInt();
|
if (o instanceof Range) return ((Range) o).randInt();
|
||||||
if (o instanceof Boolean) return ((Boolean) o) ? 1 : 0;
|
if (o instanceof Boolean) return ((Boolean) o) ? 1 : 0;
|
||||||
} catch (NumberFormatException e) {}
|
} catch (final NumberFormatException e) {}
|
||||||
Log.w("Cannot convert " + o + " to Integer.");
|
Log.w("Cannot convert " + o + " to Integer.");
|
||||||
return def;
|
return def;
|
||||||
}
|
}
|
||||||
@@ -50,7 +50,7 @@ public class Convertor {
|
|||||||
if (o instanceof Number) return ((Number) o).doubleValue();
|
if (o instanceof Number) return ((Number) o).doubleValue();
|
||||||
if (o instanceof Range) return ((Range) o).randDouble();
|
if (o instanceof Range) return ((Range) o).randDouble();
|
||||||
if (o instanceof Boolean) return ((Boolean) o) ? 1 : 0;
|
if (o instanceof Boolean) return ((Boolean) o) ? 1 : 0;
|
||||||
} catch (NumberFormatException e) {}
|
} catch (final NumberFormatException e) {}
|
||||||
Log.w("Cannot convert " + o + " to Double.");
|
Log.w("Cannot convert " + o + " to Double.");
|
||||||
return def;
|
return def;
|
||||||
}
|
}
|
||||||
@@ -68,7 +68,7 @@ public class Convertor {
|
|||||||
try {
|
try {
|
||||||
if (o == null) return def;
|
if (o == null) return def;
|
||||||
if (o instanceof Number) return ((Number) o).floatValue();
|
if (o instanceof Number) return ((Number) o).floatValue();
|
||||||
} catch (NumberFormatException e) {}
|
} catch (final NumberFormatException e) {}
|
||||||
Log.w("Cannot convert " + o + " to Float.");
|
Log.w("Cannot convert " + o + " to Float.");
|
||||||
return def;
|
return def;
|
||||||
}
|
}
|
||||||
@@ -86,13 +86,13 @@ public class Convertor {
|
|||||||
if (o == null) return def;
|
if (o == null) return def;
|
||||||
|
|
||||||
if (o instanceof String) {
|
if (o instanceof String) {
|
||||||
String s = ((String) o).trim().toLowerCase();
|
final String s = ((String) o).trim().toLowerCase();
|
||||||
if (s.equals("0")) return false;
|
if (s.equals("0")) return false;
|
||||||
if (s.equals("1")) return true;
|
if (s.equals("1")) return true;
|
||||||
try {
|
try {
|
||||||
double n = Double.parseDouble(s);
|
final double n = Double.parseDouble(s);
|
||||||
return n != 0;
|
return n != 0;
|
||||||
} catch (NumberFormatException e) {}
|
} catch (final NumberFormatException e) {}
|
||||||
|
|
||||||
if (s.equals("true")) return true;
|
if (s.equals("true")) return true;
|
||||||
if (s.equals("yes")) return true;
|
if (s.equals("yes")) return true;
|
||||||
@@ -149,11 +149,11 @@ public class Convertor {
|
|||||||
s = s.replace(',', ';');
|
s = s.replace(',', ';');
|
||||||
// remove brackets if any
|
// remove brackets if any
|
||||||
s = s.replaceAll("[\\(\\[\\{\\)\\]\\}]", "");
|
s = s.replaceAll("[\\(\\[\\{\\)\\]\\}]", "");
|
||||||
String[] parts = s.split("[;]");
|
final String[] parts = s.split("[;]");
|
||||||
return new Coord(Double.parseDouble(parts[0].trim()), Double.parseDouble(parts[1].trim()));
|
return new Coord(Double.parseDouble(parts[0].trim()), Double.parseDouble(parts[1].trim()));
|
||||||
}
|
}
|
||||||
if (o instanceof Coord) return new Coord((Coord) o);
|
if (o instanceof Coord) return new Coord((Coord) o);
|
||||||
} catch (NumberFormatException e) {
|
} catch (final NumberFormatException e) {
|
||||||
// ignore
|
// ignore
|
||||||
}
|
}
|
||||||
Log.w("Cannot convert " + o + " to Coord.");
|
Log.w("Cannot convert " + o + " to Coord.");
|
||||||
@@ -184,13 +184,13 @@ public class Convertor {
|
|||||||
s = s.replaceAll("([0-9])\\s?[\\-]", "$1:");
|
s = s.replaceAll("([0-9])\\s?[\\-]", "$1:");
|
||||||
// remove brackets if any
|
// remove brackets if any
|
||||||
s = s.replaceAll("[\\(\\[\\{\\)\\]\\}]", "");
|
s = s.replaceAll("[\\(\\[\\{\\)\\]\\}]", "");
|
||||||
String[] parts = s.split("[:]");
|
final String[] parts = s.split("[:]");
|
||||||
if (parts.length == 2) return new Range(Double.parseDouble(parts[0].trim()), Double.parseDouble(parts[1].trim()));
|
if (parts.length == 2) return new Range(Double.parseDouble(parts[0].trim()), Double.parseDouble(parts[1].trim()));
|
||||||
return new Range(Double.parseDouble(parts[0].trim()), Double.parseDouble(parts[0].trim()));
|
return new Range(Double.parseDouble(parts[0].trim()), Double.parseDouble(parts[0].trim()));
|
||||||
|
|
||||||
}
|
}
|
||||||
if (o instanceof Range) return (Range) o;
|
if (o instanceof Range) return (Range) o;
|
||||||
} catch (NumberFormatException e) {}
|
} catch (final NumberFormatException e) {}
|
||||||
Log.w("Cannot convert " + o + " to Range.");
|
Log.w("Cannot convert " + o + " to Range.");
|
||||||
return def;
|
return def;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package mightypork.utils.objects;
|
||||||
|
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.Map.Entry;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map sorting utils
|
||||||
|
*
|
||||||
|
* @author MightyPork
|
||||||
|
*/
|
||||||
|
public class MapSort {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sort a map by keys, maintaining key-value pairs.
|
||||||
|
*
|
||||||
|
* @param map map to be sorted
|
||||||
|
* @param comparator a comparator, or null for natural ordering
|
||||||
|
* @return linked hash map with sorted entries
|
||||||
|
*/
|
||||||
|
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||||
|
public static <K extends Comparable, V extends Comparable> Map<K, V> sortByKeys(Map<K, V> map, final Comparator<K> comparator)
|
||||||
|
{
|
||||||
|
final List<K> keys = new LinkedList<K>(map.keySet());
|
||||||
|
|
||||||
|
if (comparator == null) {
|
||||||
|
Collections.sort(keys);
|
||||||
|
} else {
|
||||||
|
Collections.sort(keys, comparator);
|
||||||
|
}
|
||||||
|
|
||||||
|
// LinkedHashMap will keep the keys in the order they are inserted
|
||||||
|
// which is currently sorted on natural ordering
|
||||||
|
final Map<K, V> sortedMap = new LinkedHashMap<K, V>();
|
||||||
|
for (final K key : keys) {
|
||||||
|
sortedMap.put(key, map.get(key));
|
||||||
|
}
|
||||||
|
|
||||||
|
return sortedMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sort a map by values, maintaining key-value pairs.
|
||||||
|
*
|
||||||
|
* @param map map to be sorted
|
||||||
|
* @param comparator a comparator, or null for natural ordering
|
||||||
|
* @return linked hash map with sorted entries
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("rawtypes")
|
||||||
|
public static <K extends Comparable, V extends Comparable> Map<K, V> sortByValues(Map<K, V> map, final Comparator<V> comparator)
|
||||||
|
{
|
||||||
|
final List<Map.Entry<K, V>> entries = new LinkedList<Map.Entry<K, V>>(map.entrySet());
|
||||||
|
|
||||||
|
Collections.sort(entries, new Comparator<Map.Entry<K, V>>() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int compare(Entry<K, V> o1, Entry<K, V> o2)
|
||||||
|
{
|
||||||
|
if (comparator == null) return o1.getValue().compareTo(o2.getValue());
|
||||||
|
return comparator.compare(o1.getValue(), o2.getValue());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// LinkedHashMap will keep the keys in the order they are inserted
|
||||||
|
// which is currently sorted on natural ordering
|
||||||
|
final Map<K, V> sortedMap = new LinkedHashMap<K, V>();
|
||||||
|
|
||||||
|
for (final Map.Entry<K, V> entry : entries) {
|
||||||
|
sortedMap.put(entry.getKey(), entry.getValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
return sortedMap;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -62,7 +62,7 @@ public class Mutable<T> {
|
|||||||
if (obj == null) return false;
|
if (obj == null) return false;
|
||||||
if (!(obj instanceof Mutable)) return false;
|
if (!(obj instanceof Mutable)) return false;
|
||||||
|
|
||||||
Mutable<?> other = (Mutable<?>) obj;
|
final Mutable<?> other = (Mutable<?>) obj;
|
||||||
if (o == null) {
|
if (o == null) {
|
||||||
if (other.o != null) return false;
|
if (other.o != null) return false;
|
||||||
} else if (!o.equals(other.o)) {
|
} else if (!o.equals(other.o)) {
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
package mightypork.utils.objects;
|
package mightypork.utils.objects;
|
||||||
|
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.ArrayList;
|
||||||
import java.util.Map.Entry;
|
import java.util.List;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -14,83 +14,20 @@ public class ObjectUtils {
|
|||||||
|
|
||||||
public static Object fallback(Object... options)
|
public static Object fallback(Object... options)
|
||||||
{
|
{
|
||||||
for (Object o : options) {
|
for (final Object o : options) {
|
||||||
if (o != null) return o;
|
if (o != null) return o;
|
||||||
}
|
}
|
||||||
return null; // error
|
return null; // error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sort a map by keys, maintaining key-value pairs.
|
|
||||||
*
|
|
||||||
* @param map map to be sorted
|
|
||||||
* @param comparator a comparator, or null for natural ordering
|
|
||||||
* @return linked hash map with sorted entries
|
|
||||||
*/
|
|
||||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
|
||||||
public static <K extends Comparable, V extends Comparable> Map<K, V> sortByKeys(Map<K, V> map, final Comparator<K> comparator)
|
|
||||||
{
|
|
||||||
List<K> keys = new LinkedList<K>(map.keySet());
|
|
||||||
|
|
||||||
if (comparator == null) {
|
|
||||||
Collections.sort(keys);
|
|
||||||
} else {
|
|
||||||
Collections.sort(keys, comparator);
|
|
||||||
}
|
|
||||||
|
|
||||||
// LinkedHashMap will keep the keys in the order they are inserted
|
|
||||||
// which is currently sorted on natural ordering
|
|
||||||
Map<K, V> sortedMap = new LinkedHashMap<K, V>();
|
|
||||||
for (K key : keys) {
|
|
||||||
sortedMap.put(key, map.get(key));
|
|
||||||
}
|
|
||||||
|
|
||||||
return sortedMap;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sort a map by values, maintaining key-value pairs.
|
|
||||||
*
|
|
||||||
* @param map map to be sorted
|
|
||||||
* @param comparator a comparator, or null for natural ordering
|
|
||||||
* @return linked hash map with sorted entries
|
|
||||||
*/
|
|
||||||
@SuppressWarnings("rawtypes")
|
|
||||||
public static <K extends Comparable, V extends Comparable> Map<K, V> sortByValues(Map<K, V> map, final Comparator<V> comparator)
|
|
||||||
{
|
|
||||||
List<Map.Entry<K, V>> entries = new LinkedList<Map.Entry<K, V>>(map.entrySet());
|
|
||||||
|
|
||||||
Collections.sort(entries, new Comparator<Map.Entry<K, V>>() {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int compare(Entry<K, V> o1, Entry<K, V> o2)
|
|
||||||
{
|
|
||||||
if (comparator == null) return o1.getValue().compareTo(o2.getValue());
|
|
||||||
return comparator.compare(o1.getValue(), o2.getValue());
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// LinkedHashMap will keep the keys in the order they are inserted
|
|
||||||
// which is currently sorted on natural ordering
|
|
||||||
Map<K, V> sortedMap = new LinkedHashMap<K, V>();
|
|
||||||
|
|
||||||
for (Map.Entry<K, V> entry : entries) {
|
|
||||||
sortedMap.put(entry.getKey(), entry.getValue());
|
|
||||||
}
|
|
||||||
|
|
||||||
return sortedMap;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public static String arrayToString(Object[] arr)
|
public static String arrayToString(Object[] arr)
|
||||||
{
|
{
|
||||||
StringBuilder sb = new StringBuilder();
|
final StringBuilder sb = new StringBuilder();
|
||||||
|
|
||||||
sb.append('[');
|
sb.append('[');
|
||||||
boolean first = true;
|
final boolean first = true;
|
||||||
for (Object o : arr) {
|
for (final Object o : arr) {
|
||||||
if (!first) sb.append(',');
|
if (!first) sb.append(',');
|
||||||
sb.append(o.toString());
|
sb.append(o.toString());
|
||||||
}
|
}
|
||||||
@@ -102,8 +39,8 @@ public class ObjectUtils {
|
|||||||
|
|
||||||
public static <T extends Object> List<T> arrayToList(T[] objs)
|
public static <T extends Object> List<T> arrayToList(T[] objs)
|
||||||
{
|
{
|
||||||
ArrayList<T> list = new ArrayList<T>();
|
final ArrayList<T> list = new ArrayList<T>();
|
||||||
for (T o : objs) {
|
for (final T o : objs) {
|
||||||
list.add(o);
|
list.add(o);
|
||||||
}
|
}
|
||||||
return list;
|
return list;
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ public class Pair<T1, T2> {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
Pair<?, ?> t = (Pair<?, ?>) obj;
|
final Pair<?, ?> t = (Pair<?, ?>) obj;
|
||||||
|
|
||||||
return Calc.areObjectsEqual(first, t.first) && Calc.areObjectsEqual(second, t.second);
|
return Calc.areObjectsEqual(first, t.first) && Calc.areObjectsEqual(second, t.second);
|
||||||
|
|
||||||
|
|||||||
@@ -32,14 +32,14 @@ public class VarargsParser<K, V> {
|
|||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
public Map<K, V> parse(Object... args) throws ClassCastException, IllegalArgumentException
|
public Map<K, V> parse(Object... args) throws ClassCastException, IllegalArgumentException
|
||||||
{
|
{
|
||||||
LinkedHashMap<K, V> attrs = new LinkedHashMap<K, V>();
|
final LinkedHashMap<K, V> attrs = new LinkedHashMap<K, V>();
|
||||||
|
|
||||||
if (args.length % 2 != 0) {
|
if (args.length % 2 != 0) {
|
||||||
throw new IllegalArgumentException("Odd number of elements in varargs map!");
|
throw new IllegalArgumentException("Odd number of elements in varargs map!");
|
||||||
}
|
}
|
||||||
|
|
||||||
K key = null;
|
K key = null;
|
||||||
for (Object o : args) {
|
for (final Object o : args) {
|
||||||
if (key == null) {
|
if (key == null) {
|
||||||
if (o == null) throw new RuntimeException("Key cannot be NULL in varargs map.");
|
if (o == null) throw new RuntimeException("Key cannot be NULL in varargs map.");
|
||||||
key = (K) o;
|
key = (K) o;
|
||||||
|
|||||||
@@ -19,12 +19,12 @@ public class StringUtils {
|
|||||||
public static boolean isInArray(String needle, boolean case_sensitive, String... haystack)
|
public static boolean isInArray(String needle, boolean case_sensitive, String... haystack)
|
||||||
{
|
{
|
||||||
if (case_sensitive) {
|
if (case_sensitive) {
|
||||||
for (String s : haystack) {
|
for (final String s : haystack) {
|
||||||
if (needle.equals(s)) return true;
|
if (needle.equals(s)) return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
} else {
|
} else {
|
||||||
for (String s : haystack) {
|
for (final String s : haystack) {
|
||||||
if (needle.equalsIgnoreCase(s)) return true;
|
if (needle.equalsIgnoreCase(s)) return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
@@ -124,9 +124,9 @@ public class StringUtils {
|
|||||||
*/
|
*/
|
||||||
public static String formatInt(long number)
|
public static String formatInt(long number)
|
||||||
{
|
{
|
||||||
String num = number + "";
|
final String num = number + "";
|
||||||
String out = "";
|
String out = "";
|
||||||
String dot = ".";
|
final String dot = ".";
|
||||||
int cnt = 1;
|
int cnt = 1;
|
||||||
for (int i = num.length() - 1; i >= 0; i--) {
|
for (int i = num.length() - 1; i >= 0; i--) {
|
||||||
out = num.charAt(i) + out;
|
out = num.charAt(i) + out;
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ package mightypork.utils.string.validation;
|
|||||||
|
|
||||||
public class CharValidatorRegex implements CharValidator {
|
public class CharValidatorRegex implements CharValidator {
|
||||||
|
|
||||||
private String formula;
|
private final String formula;
|
||||||
|
|
||||||
|
|
||||||
public CharValidatorRegex(String regex) {
|
public CharValidatorRegex(String regex) {
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ package mightypork.utils.string.validation;
|
|||||||
|
|
||||||
public class CharValidatorWhitelist implements CharValidator {
|
public class CharValidatorWhitelist implements CharValidator {
|
||||||
|
|
||||||
private String whitelist;
|
private final String whitelist;
|
||||||
|
|
||||||
|
|
||||||
public CharValidatorWhitelist(String allowed) {
|
public CharValidatorWhitelist(String allowed) {
|
||||||
|
|||||||
@@ -31,9 +31,9 @@ public class FileSuffixFilter implements FileFilter {
|
|||||||
{
|
{
|
||||||
if (!pathname.isFile()) return false;
|
if (!pathname.isFile()) return false;
|
||||||
|
|
||||||
String fname = pathname.getName().toLowerCase().trim();
|
final String fname = pathname.getName().toLowerCase().trim();
|
||||||
|
|
||||||
for (String suffix : suffixes) {
|
for (final String suffix : suffixes) {
|
||||||
if (fname.endsWith(suffix.toLowerCase().trim())) {
|
if (fname.endsWith(suffix.toLowerCase().trim())) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user