Converted to Java 7, factored InstanceLock to own file.

v5stable
Ondřej Hruška 11 years ago
parent 6460ad9029
commit e4e7aa7eb3
  1. 2
      .classpath
  2. 11
      .settings/org.eclipse.jdt.core.prefs
  3. 5
      src/mightypork/gamecore/audio/JointVolume.java
  4. 4
      src/mightypork/gamecore/audio/SoundBank.java
  5. 12
      src/mightypork/gamecore/audio/SoundSystem.java
  6. 21
      src/mightypork/gamecore/audio/Volume.java
  7. 10
      src/mightypork/gamecore/audio/players/BaseAudioPlayer.java
  8. 4
      src/mightypork/gamecore/audio/players/EffectPlayer.java
  9. 4
      src/mightypork/gamecore/audio/players/LoopPlayer.java
  10. 4
      src/mightypork/gamecore/control/GameLoop.java
  11. 4
      src/mightypork/gamecore/control/bus/BufferedHashSet.java
  12. 2
      src/mightypork/gamecore/control/bus/BusAccess.java
  13. 10
      src/mightypork/gamecore/control/bus/EventBus.java
  14. 4
      src/mightypork/gamecore/control/bus/EventChannel.java
  15. 4
      src/mightypork/gamecore/control/bus/clients/BusNode.java
  16. 1
      src/mightypork/gamecore/control/bus/clients/RootBusNode.java
  17. 2
      src/mightypork/gamecore/control/interf/NoImpl.java
  18. 2
      src/mightypork/gamecore/control/timing/FpsMeter.java
  19. 2
      src/mightypork/gamecore/gui/renderers/ElementHolder.java
  20. 8
      src/mightypork/gamecore/gui/renderers/TextPainter.java
  21. 2
      src/mightypork/gamecore/gui/screens/LayeredScreen.java
  22. 12
      src/mightypork/gamecore/gui/screens/ScreenLayer.java
  23. 2
      src/mightypork/gamecore/gui/screens/ScreenRegistry.java
  24. 2
      src/mightypork/gamecore/input/InputSystem.java
  25. 2
      src/mightypork/gamecore/input/KeyBindingPool.java
  26. 2
      src/mightypork/gamecore/input/KeyStroke.java
  27. 2
      src/mightypork/gamecore/loading/AsyncResourceLoader.java
  28. 3
      src/mightypork/gamecore/render/DisplaySystem.java
  29. 1
      src/mightypork/gamecore/render/Render.java
  30. 8
      src/mightypork/gamecore/render/Screenshot.java
  31. 16
      src/mightypork/gamecore/render/fonts/DeferredFont.java
  32. 5
      src/mightypork/gamecore/render/fonts/FontBank.java
  33. 7
      src/mightypork/gamecore/render/fonts/FontRenderer.java
  34. 3
      src/mightypork/gamecore/render/fonts/SlickFont.java
  35. 2
      src/mightypork/gamecore/render/textures/FilterMode.java
  36. 4
      src/mightypork/gamecore/render/textures/TextureBank.java
  37. 2
      src/mightypork/gamecore/render/textures/WrapMode.java
  38. 45
      src/mightypork/rogue/App.java
  39. 1
      src/mightypork/rogue/Paths.java
  40. 4
      src/mightypork/rogue/screens/LayerFps.java
  41. 4
      src/mightypork/rogue/screens/test_bouncyboxes/LayerBouncyBoxes.java
  42. 1
      src/mightypork/rogue/screens/test_bouncyboxes/ScreenTestBouncy.java
  43. 2
      src/mightypork/rogue/screens/test_cat_sound/LayerFlyingCat.java
  44. 2
      src/mightypork/rogue/screens/test_cat_sound/ScreenTestCat.java
  45. 4
      src/mightypork/rogue/screens/test_font/ScreenTestFont.java
  46. 28
      src/mightypork/utils/config/PropertyManager.java
  47. 6
      src/mightypork/utils/config/SimpleConfig.java
  48. 4
      src/mightypork/utils/config/SortedProperties.java
  49. 42
      src/mightypork/utils/files/FileTreeDiff.java
  50. 63
      src/mightypork/utils/files/FileUtils.java
  51. 51
      src/mightypork/utils/files/InstanceLock.java
  52. 8
      src/mightypork/utils/files/ZipBuilder.java
  53. 68
      src/mightypork/utils/files/ZipUtils.java
  54. 29
      src/mightypork/utils/files/ion/Ion.java
  55. 2
      src/mightypork/utils/logging/Log.java
  56. 2
      src/mightypork/utils/logging/LogInstance.java
  57. 2
      src/mightypork/utils/math/Calc.java
  58. 23
      src/mightypork/utils/math/constraints/ConstraintFactory.java
  59. 2
      src/mightypork/utils/math/coord/Coord.java
  60. 12
      src/mightypork/utils/objects/Convert.java
  61. 8
      src/mightypork/utils/objects/MapSort.java
  62. 2
      src/mightypork/utils/objects/ObjectUtils.java
  63. 2
      src/mightypork/utils/objects/VarargsParser.java
  64. 1
      src/mightypork/utils/string/StringProvider.java

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<classpath> <classpath>
<classpathentry kind="src" path="src"/> <classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
<classpathentry kind="lib" path="lib/jinput.jar" sourcepath="lib/lwjgl-source-2.8.4.zip"> <classpathentry kind="lib" path="lib/jinput.jar" sourcepath="lib/lwjgl-source-2.8.4.zip">
<attributes> <attributes>
<attribute name="org.eclipse.jdt.launching.CLASSPATH_ATTR_LIBRARY_PATH_ENTRY" value="Rogue/lib"/> <attribute name="org.eclipse.jdt.launching.CLASSPATH_ATTR_LIBRARY_PATH_ENTRY" value="Rogue/lib"/>

@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.7
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.7

@ -10,7 +10,7 @@ import mightypork.utils.objects.Mutable;
* *
* @author MightyPork * @author MightyPork
*/ */
public class JointVolume extends Mutable<Double> { public class JointVolume extends Volume {
private final Mutable<Double>[] volumes; private final Mutable<Double>[] volumes;
@ -20,7 +20,8 @@ public class JointVolume extends Mutable<Double> {
* *
* @param volumes individual volumes to join * @param volumes individual volumes to join
*/ */
public JointVolume(Mutable<Double>... volumes) { @SafeVarargs
public JointVolume(Volume... volumes) {
super(1D); super(1D);
this.volumes = volumes; this.volumes = volumes;
} }

@ -17,8 +17,8 @@ public class SoundBank extends AppAdapter {
private static final LoopPlayer NULL_LOOP = new LoopPlayer(NO_SOUND, 0, 0, null); private static final LoopPlayer NULL_LOOP = new LoopPlayer(NO_SOUND, 0, 0, null);
private static final EffectPlayer NULL_EFFECT = new EffectPlayer(NO_SOUND, 0, 0, null); private static final EffectPlayer NULL_EFFECT = new EffectPlayer(NO_SOUND, 0, 0, null);
private final Map<String, EffectPlayer> effects = new HashMap<String, EffectPlayer>(); private final Map<String, EffectPlayer> effects = new HashMap<>();
private final Map<String, LoopPlayer> loops = new HashMap<String, LoopPlayer>(); private final Map<String, LoopPlayer> loops = new HashMap<>();
public SoundBank(AppAccess app) { public SoundBank(AppAccess app) {

@ -13,7 +13,6 @@ import mightypork.gamecore.control.bus.events.ResourceLoadRequest;
import mightypork.gamecore.control.interf.Updateable; import mightypork.gamecore.control.interf.Updateable;
import mightypork.utils.math.Calc.Buffers; import mightypork.utils.math.Calc.Buffers;
import mightypork.utils.math.coord.Coord; import mightypork.utils.math.coord.Coord;
import mightypork.utils.objects.Mutable;
import org.lwjgl.openal.AL; import org.lwjgl.openal.AL;
import org.lwjgl.openal.AL10; import org.lwjgl.openal.AL10;
@ -25,7 +24,6 @@ import org.newdawn.slick.openal.SoundStore;
* *
* @author MightyPork * @author MightyPork
*/ */
@SuppressWarnings("unchecked")
public class SoundSystem extends RootBusNode implements Updateable { public class SoundSystem extends RootBusNode implements Updateable {
private static final Coord INITIAL_LISTENER_POS = new Coord(0, 0, 0); private static final Coord INITIAL_LISTENER_POS = new Coord(0, 0, 0);
@ -72,12 +70,12 @@ public class SoundSystem extends RootBusNode implements Updateable {
// -- instance -- // -- instance --
public final Mutable<Double> masterVolume = new Mutable<Double>(1D); public final Volume masterVolume = new Volume(1D);
public final Mutable<Double> effectsVolume = new JointVolume(masterVolume); public final Volume effectsVolume = new JointVolume(masterVolume);
public final Mutable<Double> loopsVolume = new JointVolume(masterVolume); public final Volume loopsVolume = new JointVolume(masterVolume);
private final Set<LoopPlayer> loopPlayers = new HashSet<LoopPlayer>(); private final Set<LoopPlayer> loopPlayers = new HashSet<>();
private final Set<DeferredAudio> resources = new HashSet<DeferredAudio>(); private final Set<DeferredAudio> resources = new HashSet<>();
public SoundSystem(AppAccess app) { public SoundSystem(AppAccess app) {

@ -0,0 +1,21 @@
package mightypork.gamecore.audio;
import mightypork.utils.math.Calc;
import mightypork.utils.objects.Mutable;
public class Volume extends Mutable<Double> {
public Volume(Double d) {
super(d);
}
@Override
public void set(Double d)
{
super.set(Calc.clampd(d, 0, 1));
}
}

@ -2,8 +2,8 @@ package mightypork.gamecore.audio.players;
import mightypork.gamecore.audio.DeferredAudio; import mightypork.gamecore.audio.DeferredAudio;
import mightypork.gamecore.audio.Volume;
import mightypork.gamecore.control.interf.Destroyable; import mightypork.gamecore.control.interf.Destroyable;
import mightypork.utils.objects.Mutable;
public abstract class BaseAudioPlayer implements Destroyable { public abstract class BaseAudioPlayer implements Destroyable {
@ -18,21 +18,21 @@ public abstract class BaseAudioPlayer implements Destroyable {
private final double basePitch; private final double basePitch;
/** dedicated volume control */ /** dedicated volume control */
private final Mutable<Double> gainMultiplier; private final Volume gainMultiplier;
public BaseAudioPlayer(DeferredAudio track, double baseGain, Mutable<Double> gainMultiplier) { public BaseAudioPlayer(DeferredAudio track, double baseGain, Volume gainMultiplier) {
this(track, 1, baseGain, gainMultiplier); this(track, 1, baseGain, gainMultiplier);
} }
public BaseAudioPlayer(DeferredAudio track, double basePitch, double baseGain, Mutable<Double> gainMultiplier) { public BaseAudioPlayer(DeferredAudio track, double basePitch, double baseGain, Volume gainMultiplier) {
this.audio = track; this.audio = track;
this.baseGain = baseGain; this.baseGain = baseGain;
this.basePitch = basePitch; this.basePitch = basePitch;
if (gainMultiplier == null) gainMultiplier = new Mutable<Double>(1D); if (gainMultiplier == null) gainMultiplier = new Volume(1D);
this.gainMultiplier = gainMultiplier; this.gainMultiplier = gainMultiplier;
} }

@ -2,13 +2,13 @@ package mightypork.gamecore.audio.players;
import mightypork.gamecore.audio.DeferredAudio; import mightypork.gamecore.audio.DeferredAudio;
import mightypork.gamecore.audio.Volume;
import mightypork.utils.math.coord.Coord; import mightypork.utils.math.coord.Coord;
import mightypork.utils.objects.Mutable;
public class EffectPlayer extends BaseAudioPlayer { public class EffectPlayer extends BaseAudioPlayer {
public EffectPlayer(DeferredAudio track, double basePitch, double baseGain, Mutable<Double> gainMultiplier) { public EffectPlayer(DeferredAudio track, double basePitch, double baseGain, Volume gainMultiplier) {
super(track, (float) basePitch, (float) baseGain, gainMultiplier); super(track, (float) basePitch, (float) baseGain, gainMultiplier);
} }

@ -2,10 +2,10 @@ package mightypork.gamecore.audio.players;
import mightypork.gamecore.audio.DeferredAudio; import mightypork.gamecore.audio.DeferredAudio;
import mightypork.gamecore.audio.Volume;
import mightypork.gamecore.control.interf.Updateable; import mightypork.gamecore.control.interf.Updateable;
import mightypork.gamecore.control.timing.Pauseable; import mightypork.gamecore.control.timing.Pauseable;
import mightypork.utils.math.animation.AnimDouble; import mightypork.utils.math.animation.AnimDouble;
import mightypork.utils.objects.Mutable;
import org.lwjgl.openal.AL10; import org.lwjgl.openal.AL10;
@ -29,7 +29,7 @@ public class LoopPlayer extends BaseAudioPlayer implements Updateable, Pauseable
private double outTime = 1; private double outTime = 1;
public LoopPlayer(DeferredAudio track, double pitch, double baseGain, Mutable<Double> gainMultiplier) { public LoopPlayer(DeferredAudio track, double pitch, double baseGain, Volume gainMultiplier) {
super(track, (float) pitch, (float) baseGain, gainMultiplier); super(track, (float) pitch, (float) baseGain, gainMultiplier);
paused = true; paused = true;

@ -19,9 +19,9 @@ import mightypork.gamecore.gui.screens.ScreenRegistry;
*/ */
public abstract class GameLoop extends AppModule implements MainLoopTaskRequest.Listener { public abstract class GameLoop extends AppModule implements MainLoopTaskRequest.Listener {
private final Queue<Runnable> taskQueue = new ConcurrentLinkedQueue<Runnable>(); private final Queue<Runnable> taskQueue = new ConcurrentLinkedQueue<>();
private TimerDelta timer; private TimerDelta timer;
private Renderable mainRenderable; private final Renderable mainRenderable;
private boolean running = true; private boolean running = true;

@ -16,8 +16,8 @@ import java.util.List;
*/ */
public class BufferedHashSet<E> extends HashSet<E> { public class BufferedHashSet<E> extends HashSet<E> {
private final List<E> toAdd = new LinkedList<E>(); private final List<E> toAdd = new LinkedList<>();
private final List<Object> toRemove = new LinkedList<Object>(); private final List<Object> toRemove = new LinkedList<>();
private boolean buffering = false; private boolean buffering = false;

@ -1,8 +1,6 @@
package mightypork.gamecore.control.bus; package mightypork.gamecore.control.bus;
/** /**
* Access to an {@link EventBus} instance * Access to an {@link EventBus} instance
* *

@ -22,13 +22,13 @@ import mightypork.utils.logging.Log;
final public class EventBus implements Destroyable { final public class EventBus implements Destroyable {
/** Message channels */ /** Message channels */
private final BufferedHashSet<EventChannel<?, ?>> channels = new BufferedHashSet<EventChannel<?, ?>>(); private final BufferedHashSet<EventChannel<?, ?>> channels = new BufferedHashSet<>();
/** Registered clients */ /** Registered clients */
private final BufferedHashSet<Object> clients = new BufferedHashSet<Object>(); private final BufferedHashSet<Object> clients = new BufferedHashSet<>();
/** Messages queued for delivery */ /** Messages queued for delivery */
private final DelayQueue<DelayQueueEntry> sendQueue = new DelayQueue<DelayQueueEntry>(); private final DelayQueue<DelayQueueEntry> sendQueue = new DelayQueue<>();
/** Queue polling thread */ /** Queue polling thread */
private final QueuePollingThread busThread; private final QueuePollingThread busThread;
@ -235,7 +235,7 @@ final public class EventBus implements Destroyable {
clients.add(client); clients.add(client);
if(detailedLogging) Log.f3("<bus> Client joined: "+Log.str(client)); if (detailedLogging) Log.f3("<bus> Client joined: " + Log.str(client));
} }
@ -250,7 +250,7 @@ final public class EventBus implements Destroyable {
clients.remove(client); clients.remove(client);
if(detailedLogging) Log.f3("<bus> Client left: "+Log.str(client)); if (detailedLogging) Log.f3("<bus> Client left: " + Log.str(client));
} }

@ -53,7 +53,7 @@ final public class EventChannel<EVENT extends Event<CLIENT>, CLIENT> {
{ {
if (!canBroadcast(event)) return false; if (!canBroadcast(event)) return false;
return doBroadcast(eventClass.cast(event), clients, new HashSet<Object>()); return doBroadcast(eventClass.cast(event), clients, new HashSet<>());
} }
@ -151,7 +151,7 @@ final public class EventChannel<EVENT extends Event<CLIENT>, CLIENT> {
*/ */
public static <F_EVENT extends Event<F_CLIENT>, F_CLIENT> EventChannel<F_EVENT, F_CLIENT> create(Class<F_EVENT> eventClass, Class<F_CLIENT> clientClass) public static <F_EVENT extends Event<F_CLIENT>, F_CLIENT> EventChannel<F_EVENT, F_CLIENT> create(Class<F_EVENT> eventClass, Class<F_CLIENT> clientClass)
{ {
return new EventChannel<F_EVENT, F_CLIENT>(eventClass, clientClass); return new EventChannel<>(eventClass, clientClass);
} }

@ -19,7 +19,7 @@ public abstract class BusNode implements BusAccess, DelegatingClient, Toggleable
private final BusAccess busAccess; private final BusAccess busAccess;
private final Set<Object> clients = new LinkedHashSet<Object>(); private final Set<Object> clients = new LinkedHashSet<>();
private boolean listening = true; private boolean listening = true;
private boolean delegating = true; private boolean delegating = true;
@ -57,7 +57,7 @@ public abstract class BusNode implements BusAccess, DelegatingClient, Toggleable
*/ */
public final void addChildClient(Object client) public final void addChildClient(Object client)
{ {
if(client instanceof RootBusNode) { if (client instanceof RootBusNode) {
throw new IllegalArgumentException("Cannot nest RootBusNode."); throw new IllegalArgumentException("Cannot nest RootBusNode.");
} }

@ -1,5 +1,6 @@
package mightypork.gamecore.control.bus.clients; package mightypork.gamecore.control.bus.clients;
import mightypork.gamecore.control.bus.BusAccess; import mightypork.gamecore.control.bus.BusAccess;
import mightypork.gamecore.control.interf.Destroyable; import mightypork.gamecore.control.interf.Destroyable;

@ -10,7 +10,7 @@ import java.lang.annotation.Target;
@Documented @Documented
@Retention(RetentionPolicy.SOURCE) @Retention(RetentionPolicy.SOURCE)
@Target(value={ElementType.METHOD}) @Target(value = { ElementType.METHOD })
public @interface NoImpl { public @interface NoImpl {
// //
} }

@ -31,7 +31,7 @@ public class FpsMeter {
if (System.currentTimeMillis() - lastTimeMillis > 1000) { if (System.currentTimeMillis() - lastTimeMillis > 1000) {
lastSecFPS = frames; lastSecFPS = frames;
frames = 0; frames = 0;
long over = System.currentTimeMillis() - lastTimeMillis - 1000; final long over = System.currentTimeMillis() - lastTimeMillis - 1000;
lastTimeMillis = System.currentTimeMillis() - over; lastTimeMillis = System.currentTimeMillis() - over;
} }
frames++; frames++;

@ -18,7 +18,7 @@ import mightypork.utils.math.coord.Rect;
*/ */
public abstract class ElementHolder extends BusNode implements PluggableRenderable { public abstract class ElementHolder extends BusNode implements PluggableRenderable {
private final LinkedList<PluggableRenderable> elements = new LinkedList<PluggableRenderable>(); private final LinkedList<PluggableRenderable> elements = new LinkedList<>();
private RectConstraint context; private RectConstraint context;

@ -2,15 +2,13 @@ package mightypork.gamecore.gui.renderers;
import mightypork.gamecore.render.fonts.FontRenderer; import mightypork.gamecore.render.fonts.FontRenderer;
import mightypork.gamecore.render.fonts.GLFont;
import mightypork.gamecore.render.fonts.FontRenderer.Align; import mightypork.gamecore.render.fonts.FontRenderer.Align;
import mightypork.gamecore.render.fonts.GLFont;
import mightypork.utils.math.color.RGB; import mightypork.utils.math.color.RGB;
import mightypork.utils.string.StringProvider; import mightypork.utils.string.StringProvider;
import mightypork.utils.string.StringProvider.StringWrapper; import mightypork.utils.string.StringProvider.StringWrapper;
public class TextPainter extends PluggableRenderer { public class TextPainter extends PluggableRenderer {
private final FontRenderer font; private final FontRenderer font;
@ -41,6 +39,7 @@ public class TextPainter extends PluggableRenderer {
this(font, align, color, (StringProvider) null); this(font, align, color, (StringProvider) null);
} }
/** /**
* Use size specified during font init instead of size provided by * Use size specified during font init instead of size provided by
* {@link GLFont} instance (measured from tile heights.<br> * {@link GLFont} instance (measured from tile heights.<br>
@ -49,7 +48,8 @@ public class TextPainter extends PluggableRenderer {
* *
* @param enable use it * @param enable use it
*/ */
public void usePtSize(boolean enable) { public void usePtSize(boolean enable)
{
font.usePtSize(enable); font.usePtSize(enable);
} }

@ -10,7 +10,7 @@ import mightypork.gamecore.render.Render;
public abstract class LayeredScreen extends Screen { public abstract class LayeredScreen extends Screen {
private final Collection<ScreenLayer> layers = new TreeSet<ScreenLayer>(); private final Collection<ScreenLayer> layers = new TreeSet<>();
public LayeredScreen(AppAccess app) { public LayeredScreen(AppAccess app) {

@ -56,15 +56,17 @@ public abstract class ScreenLayer extends AppSubModule implements Comparable<Scr
return screen.getRect(); return screen.getRect();
} }
/**
* @return higher = on top.
*/
public abstract int getPriority();
@Override @Override
public final int compareTo(ScreenLayer o) public final int compareTo(ScreenLayer o)
{ {
return Integer.compare(getPriority(), o.getPriority()); return getPriority() - o.getPriority();
} }
/**
* @return higher = on top.
*/
public abstract int getPriority();
} }

@ -13,7 +13,7 @@ import mightypork.utils.logging.Log;
public class ScreenRegistry extends AppModule implements ScreenRequestEvent.Listener, Renderable { public class ScreenRegistry extends AppModule implements ScreenRequestEvent.Listener, Renderable {
private final HashMap<String, Screen> screens = new HashMap<String, Screen>(); private final HashMap<String, Screen> screens = new HashMap<>();
private Screen active = null; private Screen active = null;

@ -25,6 +25,8 @@ public class InputSystem extends RootBusNode implements Updateable, KeyBinder {
private final KeyBindingPool keybindings; private final KeyBindingPool keybindings;
private static boolean inited = false; private static boolean inited = false;
public InputSystem(AppAccess app) { public InputSystem(AppAccess app) {
super(app); super(app);

@ -16,7 +16,7 @@ import mightypork.utils.logging.Log;
*/ */
public class KeyBindingPool implements KeyBinder, KeyEvent.Listener { public class KeyBindingPool implements KeyBinder, KeyEvent.Listener {
private final Set<KeyBinding> bindings = new HashSet<KeyBinding>(); private final Set<KeyBinding> bindings = new HashSet<>();
/** /**

@ -15,7 +15,7 @@ import org.lwjgl.input.Keyboard;
*/ */
public class KeyStroke { public class KeyStroke {
private final Set<Integer> keys = new LinkedHashSet<Integer>(); private final Set<Integer> keys = new LinkedHashSet<>();
private final boolean fallingEdge; private final boolean fallingEdge;

@ -26,7 +26,7 @@ public class AsyncResourceLoader extends Thread implements ResourceLoadRequest.L
private final ExecutorService exs = Executors.newCachedThreadPool(); private final ExecutorService exs = Executors.newCachedThreadPool();
private final LinkedBlockingQueue<DeferredResource> toLoad = new LinkedBlockingQueue<DeferredResource>(); private final LinkedBlockingQueue<DeferredResource> toLoad = new LinkedBlockingQueue<>();
private boolean stopped; private boolean stopped;
private final BusAccess app; private final BusAccess app;

@ -200,6 +200,7 @@ public class DisplaySystem extends RootBusNode implements RectConstraint {
return new Rect(getSize()); return new Rect(getSize());
} }
/** /**
* @return current FPS * @return current FPS
*/ */
@ -208,7 +209,6 @@ public class DisplaySystem extends RootBusNode implements RectConstraint {
return fpsMeter.getFPS(); return fpsMeter.getFPS();
} }
public static final NumberConstraint width = new NumberConstraint() { public static final NumberConstraint width = new NumberConstraint() {
@Override @Override
@ -218,7 +218,6 @@ public class DisplaySystem extends RootBusNode implements RectConstraint {
} }
}; };
public static final NumberConstraint height = new NumberConstraint() { public static final NumberConstraint height = new NumberConstraint() {
@Override @Override

@ -30,6 +30,7 @@ public class Render {
private static final Coord AXIS_Y = new Coord(0, 1, 0); private static final Coord AXIS_Y = new Coord(0, 1, 0);
private static final Coord AXIS_Z = new Coord(0, 0, 1); private static final Coord AXIS_Z = new Coord(0, 0, 1);
/** /**
* Bind GL color * Bind GL color
* *

@ -17,10 +17,10 @@ import javax.imageio.ImageIO;
*/ */
public class Screenshot { public class Screenshot {
private int width; private final int width;
private int height; private final int height;
private int bpp; private final int bpp;
private ByteBuffer bytes; private final ByteBuffer bytes;
private BufferedImage image; private BufferedImage image;

@ -40,7 +40,7 @@ public class DeferredFont extends BaseDeferredResource implements GLFont {
private final double size; private final double size;
private final FontStyle style; private final FontStyle style;
private final String extraChars; private final String extraChars;
private FilterMode filter; private final FilterMode filter;
/** /**
@ -107,11 +107,8 @@ public class DeferredFont extends BaseDeferredResource implements GLFont {
*/ */
protected Font getAwtFont(String resource, float size, int style) throws FontFormatException, IOException protected Font getAwtFont(String resource, float size, int style) throws FontFormatException, IOException
{ {
InputStream in = null;
try { try (InputStream in = FileUtils.getResource(resource)) {
in = FileUtils.getResource(resource);
Font awtFont = Font.createFont(Font.TRUETYPE_FONT, in); Font awtFont = Font.createFont(Font.TRUETYPE_FONT, in);
@ -119,14 +116,8 @@ public class DeferredFont extends BaseDeferredResource implements GLFont {
awtFont = awtFont.deriveFont(style); awtFont = awtFont.deriveFont(style);
return awtFont; return awtFont;
} finally {
try {
if (in != null) in.close();
} catch (final IOException e) {
//pass
}
} }
} }
@ -171,6 +162,7 @@ public class DeferredFont extends BaseDeferredResource implements GLFont {
return font.getGlyphHeight(); return font.getGlyphHeight();
} }
@Override @Override
public int getSize() public int getSize()
{ {

@ -6,8 +6,6 @@ import java.util.HashMap;
import mightypork.gamecore.control.AppAccess; import mightypork.gamecore.control.AppAccess;
import mightypork.gamecore.control.AppAdapter; import mightypork.gamecore.control.AppAdapter;
import mightypork.gamecore.control.bus.events.ResourceLoadRequest; import mightypork.gamecore.control.bus.events.ResourceLoadRequest;
import mightypork.gamecore.render.fonts.DeferredFont.FontStyle;
import mightypork.gamecore.render.textures.FilterMode;
import mightypork.utils.logging.Log; import mightypork.utils.logging.Log;
import org.newdawn.slick.opengl.Texture; import org.newdawn.slick.opengl.Texture;
@ -22,11 +20,12 @@ public class FontBank extends AppAdapter {
private static final GLFont NULL_FONT = new NullFont(); private static final GLFont NULL_FONT = new NullFont();
public FontBank(AppAccess app) { public FontBank(AppAccess app) {
super(app); super(app);
} }
private final HashMap<String, GLFont> fonts = new HashMap<String, GLFont>(); private final HashMap<String, GLFont> fonts = new HashMap<>();
/** /**

@ -136,7 +136,8 @@ public class FontRenderer {
* Draw on screen * Draw on screen
* *
* @param text text to draw * @param text text to draw
* @param bounds drawing bounds (height for font height, horizontal bounds for align) * @param bounds drawing bounds (height for font height, horizontal bounds
* for align)
* @param align horizontal alignment (with respect to bounds) * @param align horizontal alignment (with respect to bounds)
*/ */
public void draw(String text, Rect bounds, Align align) public void draw(String text, Rect bounds, Align align)
@ -145,12 +146,12 @@ public class FontRenderer {
} }
/** /**
* Draw on screen * Draw on screen
* *
* @param text text to draw * @param text text to draw
* @param bounds drawing bounds (height for font height, horizontal bounds for align) * @param bounds drawing bounds (height for font height, horizontal bounds
* for align)
* @param align horizontal alignment (with respect to bounds) * @param align horizontal alignment (with respect to bounds)
* @param color drawing color * @param color drawing color
*/ */

@ -4,7 +4,6 @@ package mightypork.gamecore.render.fonts;
import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL11.*;
import java.awt.Font; import java.awt.Font;
import java.lang.reflect.Field;
import mightypork.gamecore.render.Render; import mightypork.gamecore.render.Render;
import mightypork.gamecore.render.textures.FilterMode; import mightypork.gamecore.render.textures.FilterMode;
@ -24,7 +23,7 @@ public class SlickFont implements GLFont {
private final TrueTypeFont ttf; private final TrueTypeFont ttf;
private FilterMode filter; private FilterMode filter;
private int fsize; private final int fsize;
/** /**

@ -1,7 +1,9 @@
package mightypork.gamecore.render.textures; package mightypork.gamecore.render.textures;
import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL11;
public enum FilterMode public enum FilterMode
{ {
LINEAR(GL11.GL_LINEAR), NEAREST(GL11.GL_NEAREST); LINEAR(GL11.GL_LINEAR), NEAREST(GL11.GL_NEAREST);

@ -22,9 +22,9 @@ public class TextureBank extends AppAdapter {
super(app); super(app);
} }
private final HashMap<String, DeferredTexture> textures = new HashMap<String, DeferredTexture>(); private final HashMap<String, DeferredTexture> textures = new HashMap<>();
private final HashMap<String, TxQuad> quads = new HashMap<String, TxQuad>(); private final HashMap<String, TxQuad> quads = new HashMap<>();
private DeferredTexture lastTx; private DeferredTexture lastTx;

@ -1,7 +1,9 @@
package mightypork.gamecore.render.textures; package mightypork.gamecore.render.textures;
import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL11;
public enum WrapMode public enum WrapMode
{ {
CLAMP(GL11.GL_CLAMP), REPEAT(GL11.GL_REPEAT); CLAMP(GL11.GL_CLAMP), REPEAT(GL11.GL_REPEAT);

@ -1,9 +1,6 @@
package mightypork.rogue; package mightypork.rogue;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;
import java.util.Locale; import java.util.Locale;
import java.util.logging.Level; import java.util.logging.Level;
@ -27,6 +24,7 @@ import mightypork.rogue.events.ActionRequest.RequestType;
import mightypork.rogue.screens.test_bouncyboxes.ScreenTestBouncy; import mightypork.rogue.screens.test_bouncyboxes.ScreenTestBouncy;
import mightypork.rogue.screens.test_cat_sound.ScreenTestCat; import mightypork.rogue.screens.test_cat_sound.ScreenTestCat;
import mightypork.rogue.screens.test_font.ScreenTestFont; import mightypork.rogue.screens.test_font.ScreenTestFont;
import mightypork.utils.files.InstanceLock;
import mightypork.utils.logging.Log; import mightypork.utils.logging.Log;
import mightypork.utils.logging.LogInstance; import mightypork.utils.logging.LogInstance;
@ -266,13 +264,13 @@ public class App implements AppAccess {
{ {
if (!Config.SINGLE_INSTANCE) return; if (!Config.SINGLE_INSTANCE) return;
if (!lockInstance()) { if (!InstanceLock.onFile(Paths.LOCK)) {
System.err.println("Working directory is locked.\nOnly one instance can run at a time."); System.err.println("Could not obtain lock.\nOnly one instance can run at a time.");
//@formatter:off //@formatter:off
JOptionPane.showMessageDialog( JOptionPane.showMessageDialog(
null, null,
"The game is already running.", "Another instance is already running.",
"Instance error", "Instance error",
JOptionPane.ERROR_MESSAGE JOptionPane.ERROR_MESSAGE
); );
@ -284,41 +282,6 @@ public class App implements AppAccess {
} }
private static boolean lockInstance()
{
final File lockFile = new File(Paths.WORKDIR, ".lock");
try {
final RandomAccessFile randomAccessFile = new RandomAccessFile(lockFile, "rw");
final FileLock fileLock = randomAccessFile.getChannel().tryLock();
if (fileLock != null) {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run()
{
try {
fileLock.release();
randomAccessFile.close();
lockFile.delete();
} catch (final Exception e) {
System.err.println("Unable to remove lock file.");
e.printStackTrace();
}
}
});
return true;
}
} catch (final Exception e) {
System.err.println("Unable to create and/or lock file.");
e.printStackTrace();
}
return false;
}
/** /**
* @return sound system of the running instance * @return sound system of the running instance
*/ */

@ -14,6 +14,7 @@ public class Paths {
public static final File LOGS = OsUtils.getWorkDir(APPDIR_NAME, "logs"); public static final File LOGS = OsUtils.getWorkDir(APPDIR_NAME, "logs");
public static final File SCREENSHOTS = OsUtils.getWorkDir(APPDIR_NAME, "screenshots"); public static final File SCREENSHOTS = OsUtils.getWorkDir(APPDIR_NAME, "screenshots");
public static final File CONFIG = new File(WORKDIR, "config.ini"); public static final File CONFIG = new File(WORKDIR, "config.ini");
public static final File LOCK = new File(WORKDIR, ".lock");
public static final String DIR_EFFECTS = "res/sounds/effects/"; public static final String DIR_EFFECTS = "res/sounds/effects/";
public static final String DIR_MUSIC = "res/sounds/music/"; public static final String DIR_MUSIC = "res/sounds/music/";

@ -15,7 +15,7 @@ import mightypork.utils.math.coord.Coord;
public class LayerFps extends ScreenLayer { public class LayerFps extends ScreenLayer {
TextPainter tp; TextPainter tp;
private FontRenderer fr; private final FontRenderer fr;
public LayerFps(Screen screen) { public LayerFps(Screen screen) {
@ -28,7 +28,7 @@ public class LayerFps extends ScreenLayer {
@Override @Override
public void render() public void render()
{ {
Coord pos = new Coord(DisplaySystem.getWidth() - 8, 8); final Coord pos = new Coord(DisplaySystem.getWidth() - 8, 8);
fr.draw(getDisplay().getFps() + " fps", pos, 32, Align.RIGHT); fr.draw(getDisplay().getFps() + " fps", pos, 32, Align.RIGHT);
} }

@ -21,7 +21,7 @@ import mightypork.utils.string.StringProvider;
public class LayerBouncyBoxes extends ScreenLayer { public class LayerBouncyBoxes extends ScreenLayer {
List<BouncyBox> boxes = new ArrayList<BouncyBox>(); List<BouncyBox> boxes = new ArrayList<>();
private RowHolder layout; private RowHolder layout;
@ -57,7 +57,7 @@ public class LayerBouncyBoxes extends ScreenLayer {
boxes.add(bbr); boxes.add(bbr);
} }
StringProvider sp = new StringProvider() { final StringProvider sp = new StringProvider() {
@Override @Override
public String getString() public String getString()

@ -33,6 +33,7 @@ public class ScreenTestBouncy extends LayeredScreen {
}); });
} }
@Override @Override
public String getId() public String getId()
{ {

@ -15,7 +15,6 @@ import mightypork.gamecore.input.InputSystem;
import mightypork.gamecore.input.KeyStroke; import mightypork.gamecore.input.KeyStroke;
import mightypork.gamecore.input.Keys; import mightypork.gamecore.input.Keys;
import mightypork.gamecore.render.DisplaySystem; import mightypork.gamecore.render.DisplaySystem;
import mightypork.gamecore.render.fonts.FontRenderer;
import mightypork.gamecore.render.fonts.FontRenderer.Align; import mightypork.gamecore.render.fonts.FontRenderer.Align;
import mightypork.rogue.Res; import mightypork.rogue.Res;
import mightypork.utils.math.animation.AnimDouble; import mightypork.utils.math.animation.AnimDouble;
@ -106,6 +105,7 @@ public class LayerFlyingCat extends ScreenLayer implements Updateable, MouseButt
text.render(); text.render();
} }
@Override @Override
public int getPriority() public int getPriority()
{ {

@ -14,8 +14,6 @@ import mightypork.rogue.screens.LayerFps;
public class ScreenTestCat extends LayeredScreen { public class ScreenTestCat extends LayeredScreen {
public ScreenTestCat(AppAccess app) { public ScreenTestCat(AppAccess app) {
super(app); super(app);

@ -1,8 +1,8 @@
package mightypork.rogue.screens.test_font; package mightypork.rogue.screens.test_font;
import mightypork.gamecore.control.AppAccess;
import static mightypork.utils.math.constraints.ConstraintFactory.*; import static mightypork.utils.math.constraints.ConstraintFactory.*;
import mightypork.gamecore.control.AppAccess;
import mightypork.gamecore.gui.renderers.TextPainter; import mightypork.gamecore.gui.renderers.TextPainter;
import mightypork.gamecore.gui.screens.Screen; import mightypork.gamecore.gui.screens.Screen;
import mightypork.gamecore.render.fonts.FontRenderer.Align; import mightypork.gamecore.render.fonts.FontRenderer.Align;
@ -22,7 +22,7 @@ public class ScreenTestFont extends Screen {
tp = new TextPainter(Res.getFont("default"), Align.CENTER, RGB.GREEN); tp = new TextPainter(Res.getFont("default"), Align.CENTER, RGB.GREEN);
tp.setText("Hello World!"); tp.setText("Hello World!");
RectConstraint strbox = c_grow(c_center(this), 0, c_div(c_height(this), 10)); final RectConstraint strbox = c_grow(c_center(this), 0, c_div(c_height(this), 10));
tp.setContext(strbox); tp.setContext(strbox);
} }

@ -1,9 +1,13 @@
package mightypork.utils.config; package mightypork.utils.config;
import java.io.*; import java.io.File;
import java.util.*; import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.TreeMap;
import mightypork.utils.math.Range; import mightypork.utils.math.Range;
import mightypork.utils.math.coord.Coord; import mightypork.utils.math.coord.Coord;
@ -155,9 +159,9 @@ public class PropertyManager {
*/ */
public PropertyManager(File file, String comment) { public PropertyManager(File file, String comment) {
this.file = file; this.file = file;
this.entries = new TreeMap<String, Property<?>>(); this.entries = new TreeMap<>();
this.overrideValues = new TreeMap<String, String>(); this.overrideValues = new TreeMap<>();
this.renameTable = new TreeMap<String, String>(); this.renameTable = new TreeMap<>();
this.fileComment = comment; this.fileComment = comment;
} }
@ -168,27 +172,19 @@ public class PropertyManager {
public void apply() public void apply()
{ {
boolean needsSave = false; boolean needsSave = false;
FileInputStream fis = null;
try {
new File(file.getParent()).mkdirs(); new File(file.getParent()).mkdirs();
fis = new FileInputStream(file);
props.load(fis);
try (FileInputStream fis = new FileInputStream(file)) {
props.load(fis);
} catch (final IOException e) { } catch (final IOException e) {
needsSave = true; needsSave = true;
props = new SortedProperties(); props = new SortedProperties();
} finally {
try {
if (fis != null) fis.close();
} catch (final IOException e) {
e.printStackTrace();
}
} }
props.cfgBlankRowBetweenSections = cfgSeparateSections; props.cfgBlankRowBetweenSections = cfgSeparateSections;
props.cfgBlankRowBeforeComment = cfgNewlineBeforeComments; props.cfgBlankRowBeforeComment = cfgNewlineBeforeComments;
final ArrayList<String> keyList = new ArrayList<String>(); final ArrayList<String> keyList = new ArrayList<>();
// rename keys // rename keys
for (final Entry<String, String> entry : renameTable.entrySet()) { for (final Entry<String, String> entry : renameTable.entrySet()) {

@ -62,7 +62,7 @@ public class SimpleConfig {
*/ */
public static List<String> listFromString(String text) public static List<String> listFromString(String text)
{ {
final List<String> list = new ArrayList<String>(); final List<String> list = new ArrayList<>();
final String[] groupsLines = text.split("\n"); final String[] groupsLines = text.split("\n");
@ -92,7 +92,7 @@ public class SimpleConfig {
*/ */
public static Map<String, String> mapFromString(String text) public static Map<String, String> mapFromString(String text)
{ {
final LinkedHashMap<String, String> pairs = new LinkedHashMap<String, String>(); final LinkedHashMap<String, String> pairs = new LinkedHashMap<>();
final String[] groupsLines = text.split("\n"); final String[] groupsLines = text.split("\n");
@ -148,7 +148,7 @@ 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
{ {
final List<String> lines = new ArrayList<String>(); final List<String> lines = new ArrayList<>();
for (final Entry<String, String> e : data.entrySet()) { for (final Entry<String, String> e : data.entrySet()) {
String key = e.getKey(); String key = e.getKey();

@ -26,7 +26,7 @@ public class SortedProperties extends java.util.Properties {
public boolean cfgBlankRowBetweenSections = true; public boolean cfgBlankRowBetweenSections = true;
/** Comments for individual keys */ /** Comments for individual keys */
private final Hashtable<String, String> keyComments = new Hashtable<String, String>(); private final Hashtable<String, String> keyComments = new Hashtable<>();
private static void writeComments(BufferedWriter bw, String comm) throws IOException private static void writeComments(BufferedWriter bw, String comm) throws IOException
@ -272,7 +272,7 @@ public class SortedProperties extends java.util.Properties {
@Override @Override
public void load(InputStream is) throws IOException public synchronized void load(InputStream is) throws IOException
{ {
load(is, "utf-8"); load(is, "utf-8");
} }

@ -23,7 +23,7 @@ public class FileTreeDiff {
private boolean logging = true; private boolean logging = true;
private final List<Tuple<File>> compared = new ArrayList<Tuple<File>>(); private final List<Tuple<File>> compared = new ArrayList<>();
private final Comparator<File> fileFirstSorter = new Comparator<File>() { private final Comparator<File> fileFirstSorter = new Comparator<File>() {
@Override @Override
@ -67,19 +67,16 @@ public class FileTreeDiff {
private void calcChecksum() throws NotEqualException private void calcChecksum() throws NotEqualException
{ {
FileInputStream in1 = null, in2 = null;
CheckedInputStream cin1 = null, cin2 = null;
for (final Tuple<File> pair : compared) { for (final Tuple<File> pair : compared) {
try {
ck1.reset(); ck1.reset();
ck2.reset(); ck2.reset();
in1 = new FileInputStream(pair.a); try ( FileInputStream in1 = new FileInputStream(pair.a);
in2 = new FileInputStream(pair.b); FileInputStream in2 = new FileInputStream(pair.b)) {
cin1 = new CheckedInputStream(in1, ck1); try ( CheckedInputStream cin1 = new CheckedInputStream(in1, ck1);
cin2 = new CheckedInputStream(in2, ck2); CheckedInputStream cin2 = new CheckedInputStream(in2, ck2)) {
while (true) { while (true) {
final int read1 = cin1.read(BUFFER); final int read1 = cin1.read(BUFFER);
@ -91,36 +88,11 @@ public class FileTreeDiff {
if (read1 == -1) break; if (read1 == -1) break;
} }
} catch (final IOException e) {
// ignore
} finally {
try {
if (cin1 != null) cin1.close();
} catch (final Exception e) {
// ignore
} }
try { } catch (final IOException e) {
if (cin2 != null) cin2.close();
} catch (final Exception e) {
// ignore
}
try {
if (in1 != null) in1.close();
} catch (final Exception e) {
// ignore
}
try {
if (in2 != null) in2.close();
} catch (final Exception e) {
// ignore // ignore
} }
}
} }
} }
@ -152,7 +124,7 @@ public class FileTreeDiff {
} }
} else { } else {
compared.add(new Tuple<File>(f1, f2)); compared.add(new Tuple<>(f1, f2));
} }
} }

@ -44,8 +44,8 @@ public class FileUtils {
} }
final String[] children = source.list(); final String[] children = source.list();
for (int i = 0; i < children.length; i++) { for (final String element : children) {
copyDirectory(new File(source, children[i]), new File(target, children[i]), filter, filesCopied); copyDirectory(new File(source, element), new File(target, element), filter, filesCopied);
} }
} else { } else {
@ -71,8 +71,8 @@ public class FileUtils {
{ {
if (source.isDirectory()) { if (source.isDirectory()) {
final String[] children = source.list(); final String[] children = source.list();
for (int i = 0; i < children.length; i++) { for (final String element : children) {
listDirectoryRecursive(new File(source, children[i]), filter, files); listDirectoryRecursive(new File(source, element), filter, files);
} }
} else { } else {
@ -94,25 +94,11 @@ public class FileUtils {
*/ */
public static void copyFile(File source, File target) throws IOException public static void copyFile(File source, File target) throws IOException
{ {
InputStream in = null;
OutputStream out = null;
try { try ( InputStream in = new FileInputStream(source);
in = new FileInputStream(source); OutputStream out = new FileOutputStream(target)) {
out = new FileOutputStream(target);
copyStream(in, out); copyStream(in, out);
} finally {
try {
if (in != null) in.close();
} catch (final IOException e) {
e.printStackTrace();
}
try {
if (out != null) out.close();
} catch (final IOException e) {
e.printStackTrace();
}
} }
} }
@ -175,10 +161,11 @@ public class FileUtils {
*/ */
public static String fileToString(File file) throws IOException public static String fileToString(File file) throws IOException
{ {
final FileInputStream fin = new FileInputStream(file); try (FileInputStream fin = new FileInputStream(file)) {
return streamToString(fin); return streamToString(fin);
} }
}
/** /**
@ -208,7 +195,7 @@ public class FileUtils {
Log.e("Error creating folder " + dir, e); Log.e("Error creating folder " + dir, e);
} }
final List<File> list = new ArrayList<File>(); final List<File> list = new ArrayList<>();
try { try {
for (final File f : dir.listFiles(filter)) { for (final File f : dir.listFiles(filter)) {
@ -374,16 +361,12 @@ public class FileUtils {
*/ */
public static void stringToFile(File file, String text) throws IOException public static void stringToFile(File file, String text) throws IOException
{ {
PrintStream out = null; try (PrintStream out = new PrintStream(new FileOutputStream(file), false, "UTF-8")) {
try {
out = new PrintStream(new FileOutputStream(file), false, "UTF-8");
out.print(text); out.print(text);
out.flush(); out.flush();
} finally {
if (out != null) out.close();
} }
} }
@ -499,26 +482,10 @@ public class FileUtils {
*/ */
public static void resourceToFile(String resname, File file) throws IOException public static void resourceToFile(String resname, File file) throws IOException
{ {
InputStream in = null; try ( InputStream in = FileUtils.getResource(resname);
OutputStream out = null; OutputStream out = new FileOutputStream(file)) {
try {
in = FileUtils.getResource(resname);
out = new FileOutputStream(file);
FileUtils.copyStream(in, out); FileUtils.copyStream(in, out);
} finally {
try {
if (in != null) in.close();
} catch (final IOException e) {
// ignore
}
try {
if (out != null) out.close();
} catch (final IOException e) {
// ignore
}
} }
} }
@ -529,10 +496,12 @@ public class FileUtils {
* *
* @param resname resource name * @param resname resource name
* @return resource as string, empty string on failure * @return resource as string, empty string on failure
* @throws IOException on fail
*/ */
public static String resourceToString(String resname) public static String resourceToString(String resname) throws IOException
{ {
final InputStream in = FileUtils.getResource(resname); try (InputStream in = FileUtils.getResource(resname)) {
return streamToString(in); return streamToString(in);
} }
}
} }

@ -0,0 +1,51 @@
package mightypork.utils.files;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;
/**
* Instance lock (avoid running twice)
*
* @author MightyPork
*/
public class InstanceLock {
@SuppressWarnings("resource")
public static boolean onFile(final File lockFile)
{
try {
final RandomAccessFile randomAccessFile = new RandomAccessFile(lockFile, "rw");
final FileLock fileLock = randomAccessFile.getChannel().tryLock();
if (fileLock != null) {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run()
{
try {
fileLock.release();
randomAccessFile.close();
lockFile.delete();
} catch (final Exception e) {
System.err.println("Unable to remove lock file.");
e.printStackTrace();
}
}
});
return true;
}
return false;
} catch (IOException e) {
return false;
}
}
}

@ -17,7 +17,7 @@ import mightypork.utils.logging.Log;
public class ZipBuilder { public class ZipBuilder {
private final ZipOutputStream out; private final ZipOutputStream out;
private final HashSet<String> included = new HashSet<String>(); private final HashSet<String> included = new HashSet<>();
/** /**
@ -70,9 +70,10 @@ public class ZipBuilder {
out.putNextEntry(new ZipEntry(path)); out.putNextEntry(new ZipEntry(path));
final InputStream in = FileUtils.stringToStream(text); try (InputStream in = FileUtils.stringToStream(text)) {
FileUtils.copyStream(in, out); FileUtils.copyStream(in, out);
} }
}
/** /**
@ -90,9 +91,10 @@ public class ZipBuilder {
out.putNextEntry(new ZipEntry(path)); out.putNextEntry(new ZipEntry(path));
final InputStream in = FileUtils.getResource(resPath); try (InputStream in = FileUtils.getResource(resPath)) {
FileUtils.copyStream(in, out); FileUtils.copyStream(in, out);
} }
}
/** /**

@ -1,11 +1,7 @@
package mightypork.utils.files; package mightypork.utils.files;
import java.io.BufferedInputStream; import java.io.*;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.List; import java.util.List;
@ -36,18 +32,8 @@ public class ZipUtils {
*/ */
public static List<String> extractZip(File file, File outputDir, StringFilter filter) throws IOException public static List<String> extractZip(File file, File outputDir, StringFilter filter) throws IOException
{ {
ZipFile zip = null; try (ZipFile zip = new ZipFile(file)) {
try {
zip = new ZipFile(file);
return extractZip(zip, outputDir, filter); return extractZip(zip, outputDir, filter);
} finally {
try {
if (zip != null) zip.close();
} catch (final IOException e) {
// ignore
}
} }
} }
@ -63,7 +49,7 @@ 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
{ {
final ArrayList<String> files = new ArrayList<String>(); final ArrayList<String> files = new ArrayList<>();
outputDir.mkdirs(); outputDir.mkdirs();
@ -102,16 +88,8 @@ public class ZipUtils {
*/ */
public static List<String> listZip(File zipFile) throws IOException public static List<String> listZip(File zipFile) throws IOException
{ {
ZipFile zip = null; try (ZipFile zip = new ZipFile(zipFile)) {
try {
zip = new ZipFile(zipFile);
return listZip(zip); return listZip(zip);
} finally {
try {
if (zip != null) zip.close();
} catch (final IOException e) {
// ignore
}
} }
} }
@ -125,7 +103,7 @@ public class ZipUtils {
*/ */
public static List<String> listZip(ZipFile zip) throws IOException public static List<String> listZip(ZipFile zip) throws IOException
{ {
final ArrayList<String> files = new ArrayList<String>(); final ArrayList<String> files = new ArrayList<>();
final Enumeration<? extends ZipEntry> zipFileEntries = zip.entries(); final Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();
@ -154,29 +132,12 @@ public class ZipUtils {
{ {
destFile.getParentFile().mkdirs(); destFile.getParentFile().mkdirs();
BufferedInputStream is = null; try ( InputStream in = zip.getInputStream(entry);
FileOutputStream fos = null; BufferedInputStream is = new BufferedInputStream(in);
BufferedOutputStream dest = null; FileOutputStream fos = new FileOutputStream(destFile);
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE)) {
try {
is = new BufferedInputStream(zip.getInputStream(entry));
fos = new FileOutputStream(destFile);
dest = new BufferedOutputStream(fos, BUFFER_SIZE);
FileUtils.copyStream(is, dest); FileUtils.copyStream(is, dest);
} finally {
try {
if (is != null) is.close();
} catch (final IOException e) {
// ignore
}
try {
if (dest != null) dest.close();
} catch (final IOException e) {
// ignore
}
} }
} }
@ -208,19 +169,10 @@ public class ZipUtils {
public static boolean entryExists(File selectedFile, String string) public static boolean entryExists(File selectedFile, String string)
{ {
ZipFile zf = null; try (ZipFile zf = new ZipFile(selectedFile)) {
try {
zf = new ZipFile(selectedFile);
return zf.getEntry(string) != null; return zf.getEntry(string) != null;
} catch (final Exception e) { } catch (final Exception e) {
return false; return false;
} finally {
try {
if (zf != null) zf.close();
} catch (final IOException e) {
// ignore
}
} }
} }

@ -16,7 +16,7 @@ import mightypork.utils.math.Calc;
public class Ion { public class Ion {
/** Ionizables<Mark, Class> */ /** Ionizables<Mark, Class> */
private static Map<Byte, Class<?>> customIonizables = new HashMap<Byte, Class<?>>(); private static Map<Byte, Class<?>> customIonizables = new HashMap<>();
// register default ionizables // register default ionizables
static { static {
@ -67,22 +67,13 @@ public class Ion {
*/ */
public static Object fromFile(File file) throws IonException public static Object fromFile(File file) throws IonException
{ {
InputStream in = null; try (InputStream in = new FileInputStream(file)) {
try {
in = new FileInputStream(file);
final Object obj = fromStream(in); final Object obj = fromStream(in);
return obj; return obj;
} catch (final IOException e) { } catch (final IOException e) {
throw new IonException("Error loading ION file.", e); throw new IonException("Error loading ION file.", e);
} finally {
if (in != null) {
try {
in.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
} }
} }
@ -122,30 +113,18 @@ public class Ion {
*/ */
public static void toFile(File path, Object obj) throws IonException public static void toFile(File path, Object obj) throws IonException
{ {
OutputStream out = null; try (OutputStream out = new FileOutputStream(path)) {
try {
final String f = path.toString(); final String f = path.toString();
final 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();
out = new FileOutputStream(path);
toStream(out, obj); toStream(out, obj);
out.flush(); out.flush();
out.close(); out.close();
} catch (final 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 {
if (out != null) {
try {
out.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
} }
} }

@ -116,7 +116,7 @@ public class Log {
staticLogging = flag; staticLogging = flag;
} }
private static HashMap<String, LogInstance> logs = new HashMap<String, LogInstance>(); private static HashMap<String, LogInstance> logs = new HashMap<>();
private static LogInstance main = null; private static LogInstance main = null;

@ -50,7 +50,7 @@ public class LogInstance {
private boolean sysout = true; private boolean sysout = true;
private int monitorId = 0; private int monitorId = 0;
private final HashMap<Integer, LogMonitor> monitors = new HashMap<Integer, LogMonitor>(); private final HashMap<Integer, LogMonitor> monitors = new HashMap<>();
private LogToSysoutMonitor sysoutMonitor; private LogToSysoutMonitor sysoutMonitor;

@ -890,7 +890,7 @@ public class Calc {
} }
final String[] parts = list.split(","); final String[] parts = list.split(",");
final ArrayList<Integer> intList = new ArrayList<Integer>(); final ArrayList<Integer> intList = new ArrayList<>();
for (final String part : parts) { for (final String part : parts) {
try { try {

@ -25,6 +25,7 @@ public class ConstraintFactory {
}; };
} }
public static NumberConstraint c_max(final Object a, final Object b) public static NumberConstraint c_max(final Object a, final Object b)
{ {
return new NumberConstraint() { return new NumberConstraint() {
@ -58,7 +59,7 @@ public class ConstraintFactory {
@Override @Override
public double getValue() public double getValue()
{ {
return a.getValue()/2; return a.getValue() / 2;
} }
}; };
} }
@ -128,6 +129,7 @@ public class ConstraintFactory {
}; };
} }
public static NumberConstraint c_add(final Object a, final Object b) public static NumberConstraint c_add(final Object a, final Object b)
{ {
return new NumberConstraint() { return new NumberConstraint() {
@ -140,6 +142,7 @@ public class ConstraintFactory {
}; };
} }
public static NumberConstraint c_sub(final Object a, final Object b) public static NumberConstraint c_sub(final Object a, final Object b)
{ {
return new NumberConstraint() { return new NumberConstraint() {
@ -178,6 +181,7 @@ public class ConstraintFactory {
}; };
} }
public static NumberConstraint c_percent(final Object whole, final Object percent) public static NumberConstraint c_percent(final Object whole, final Object percent)
{ {
return new NumberConstraint() { return new NumberConstraint() {
@ -257,7 +261,7 @@ public class ConstraintFactory {
public static RectConstraint c_shrink(RectConstraint r, Object shrink) public static RectConstraint c_shrink(RectConstraint r, Object shrink)
{ {
NumberConstraint n = n(shrink); final NumberConstraint n = n(shrink);
return c_shrink(r, n, n, n, n); return c_shrink(r, n, n, n, n);
} }
@ -293,9 +297,10 @@ public class ConstraintFactory {
}; };
} }
public static RectConstraint c_grow(RectConstraint r, Object grow) public static RectConstraint c_grow(RectConstraint r, Object grow)
{ {
NumberConstraint n = n(grow); final NumberConstraint n = n(grow);
return c_grow(r, n, n, n, n); return c_grow(r, n, n, n, n);
} }
@ -338,6 +343,7 @@ public class ConstraintFactory {
}; };
} }
public static RectConstraint c_box(final RectConstraint r, final Object width, final Object height) public static RectConstraint c_box(final RectConstraint r, final Object width, final Object height)
{ {
return new RectConstraint() { return new RectConstraint() {
@ -384,6 +390,7 @@ public class ConstraintFactory {
/** /**
* Center rect around given coords * Center rect around given coords
*
* @param r rect * @param r rect
* @param x * @param x
* @param y * @param y
@ -420,6 +427,7 @@ public class ConstraintFactory {
}; };
} }
public static RectConstraint c_move(final RectConstraint r, final Object x, final Object y) public static RectConstraint c_move(final RectConstraint r, final Object x, final Object y)
{ {
return new RectConstraint() { return new RectConstraint() {
@ -432,16 +440,19 @@ public class ConstraintFactory {
}; };
} }
/** /**
* Convert {@link Double} to {@link NumberConstraint} if needed * Convert {@link Double} to {@link NumberConstraint} if needed
*
* @param o unknown numeric value * @param o unknown numeric value
* @return converted * @return converted
*/ */
public static NumberConstraint n(final Object o) { public static NumberConstraint n(final Object o)
{
if(o instanceof NumberConstraint) return (NumberConstraint) o; if (o instanceof NumberConstraint) return (NumberConstraint) o;
if(o instanceof Number) return new NumberConstraint() { if (o instanceof Number) return new NumberConstraint() {
@Override @Override
public double getValue() public double getValue()

@ -203,7 +203,7 @@ public class Coord {
*/ */
public boolean isInRect(RectConstraint rect) public boolean isInRect(RectConstraint rect)
{ {
Rect r = rect.getRect(); final Rect r = rect.getRect();
return isInRect(r.getMin(), r.getMax()); return isInRect(r.getMin(), r.getMax());
} }

@ -120,21 +120,21 @@ public class Convert {
if (o == null) return def; if (o == null) return def;
if (o instanceof String) return ((String) o); if (o instanceof String) return ((String) o);
if(o instanceof Boolean) { if (o instanceof Boolean) {
return (Boolean) o ? "True" : "False"; return (Boolean) o ? "True" : "False";
} }
if(o instanceof Coord) { if (o instanceof Coord) {
Coord c = (Coord) o; final Coord c = (Coord) o;
return String.format("[%f:%f:%f]", c.x, c.y, c.z); return String.format("[%f:%f:%f]", c.x, c.y, c.z);
} }
if(o instanceof Range) { if (o instanceof Range) {
Range c = (Range) o; final Range c = (Range) o;
return String.format("%f:%f", c.getMin(), c.getMax()); return String.format("%f:%f", c.getMin(), c.getMax());
} }
if(o instanceof Class<?>) { if (o instanceof Class<?>) {
return Log.str(o); return Log.str(o);
} }

@ -22,7 +22,7 @@ public class MapSort {
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({ "rawtypes", "unchecked" })
public static <K extends Comparable, V extends Comparable> Map<K, V> sortByKeys(Map<K, V> map, final Comparator<K> comparator) 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()); final List<K> keys = new LinkedList<>(map.keySet());
if (comparator == null) { if (comparator == null) {
Collections.sort(keys); Collections.sort(keys);
@ -32,7 +32,7 @@ public class MapSort {
// LinkedHashMap will keep the keys in the order they are inserted // LinkedHashMap will keep the keys in the order they are inserted
// which is currently sorted on natural ordering // which is currently sorted on natural ordering
final Map<K, V> sortedMap = new LinkedHashMap<K, V>(); final Map<K, V> sortedMap = new LinkedHashMap<>();
for (final K key : keys) { for (final K key : keys) {
sortedMap.put(key, map.get(key)); sortedMap.put(key, map.get(key));
} }
@ -51,7 +51,7 @@ public class MapSort {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public static <K extends Comparable, V extends Comparable> Map<K, V> sortByValues(Map<K, V> map, final Comparator<V> comparator) 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()); final List<Map.Entry<K, V>> entries = new LinkedList<>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<K, V>>() { Collections.sort(entries, new Comparator<Map.Entry<K, V>>() {
@ -65,7 +65,7 @@ public class MapSort {
// LinkedHashMap will keep the keys in the order they are inserted // LinkedHashMap will keep the keys in the order they are inserted
// which is currently sorted on natural ordering // which is currently sorted on natural ordering
final Map<K, V> sortedMap = new LinkedHashMap<K, V>(); final Map<K, V> sortedMap = new LinkedHashMap<>();
for (final Map.Entry<K, V> entry : entries) { for (final Map.Entry<K, V> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue()); sortedMap.put(entry.getKey(), entry.getValue());

@ -39,7 +39,7 @@ public class ObjectUtils {
public static <T extends Object> List<T> arrayToList(T[] objs) public static <T extends Object> List<T> arrayToList(T[] objs)
{ {
final ArrayList<T> list = new ArrayList<T>(); final ArrayList<T> list = new ArrayList<>();
for (final T o : objs) { for (final T o : objs) {
list.add(o); list.add(o);
} }

@ -32,7 +32,7 @@ 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
{ {
final LinkedHashMap<K, V> attrs = new LinkedHashMap<K, V>(); final LinkedHashMap<K, V> attrs = new LinkedHashMap<>();
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!");

@ -24,6 +24,7 @@ public interface StringProvider {
this.value = value; this.value = value;
} }
@Override @Override
public String getString() public String getString()
{ {

Loading…
Cancel
Save