diff --git a/core/src/main/java/it/cavallium/warppi/Engine.java b/core/src/main/java/it/cavallium/warppi/Engine.java index df7b2e0b..7b9fa42d 100644 --- a/core/src/main/java/it/cavallium/warppi/Engine.java +++ b/core/src/main/java/it/cavallium/warppi/Engine.java @@ -21,15 +21,14 @@ public class Engine { private static Platform platform; private static boolean running = false; private static BehaviorSubject loadPhase = BehaviorSubject.create(); - private BehaviorSubject loaded = BehaviorSubject.create(false); + private final BehaviorSubject loaded = BehaviorSubject.create(false); private HardwareDevice hardwareDevice; - private Engine() { - } + private Engine() {} /** * Start an instance of the calculator. - * + * * @param platform * Platform implementation * @param screen @@ -43,32 +42,34 @@ public class Engine { * @throws InterruptedException * @throws IOException */ - public static void start(Platform platform, Screen screen, HardwareDisplay disp, HardwareTouchDevice touchdevice, HUD hud, - StartupArguments args) throws InterruptedException, IOException { - if (running) { + public static void start(final Platform platform, final Screen screen, final HardwareDisplay disp, + final HardwareTouchDevice touchdevice, final HUD hud, final StartupArguments args) + throws InterruptedException, IOException { + if (Engine.running) throw new RuntimeException("Already running!"); - } else { - running = true; - INSTANCE.startInstance(platform, screen, disp, touchdevice, hud, args); + else { + Engine.running = true; + Engine.INSTANCE.startInstance(platform, screen, disp, touchdevice, hud, args); } } - private void startInstance(final Platform platform, Screen screen, HardwareDisplay disp, HardwareTouchDevice touchdevice, HUD hud, - StartupArguments args) throws InterruptedException, IOException { + private void startInstance(final Platform platform, final Screen screen, final HardwareDisplay disp, + final HardwareTouchDevice touchdevice, final HUD hud, final StartupArguments args) + throws InterruptedException, IOException { Engine.platform = platform; platform.getConsoleUtils().out().println("WarpPI Calculator"); initializeEnvironment(args); - Thread currentThread = Thread.currentThread(); + final Thread currentThread = Thread.currentThread(); currentThread.setPriority(Thread.MAX_PRIORITY); Engine.getPlatform().setThreadName(currentThread, "Main thread"); - DisplayManager dm = new DisplayManager(disp, hud, screen, "WarpPI Calculator by Andrea Cavalli (@Cavallium)"); - Keyboard k = new Keyboard(); - InputManager im = new InputManager(k, touchdevice); + final DisplayManager dm = new DisplayManager(disp, hud, screen, "WarpPI Calculator by Andrea Cavalli (@Cavallium)"); + final Keyboard k = new Keyboard(); + final InputManager im = new InputManager(k, touchdevice); hardwareDevice = new HardwareDevice(dm, im); - - hardwareDevice.setup(() -> loadPhase.onNext(new LoadingStatus())); + + hardwareDevice.setup(() -> Engine.loadPhase.onNext(new LoadingStatus())); } private void onShutdown() { @@ -79,13 +80,12 @@ public class Engine { Engine.getPlatform().exit(0); } - private void initializeEnvironment(StartupArguments args) throws IOException { + private void initializeEnvironment(final StartupArguments args) throws IOException { ClassUtils.classLoader = this.getClass(); StaticVars.startupArguments = args; StaticVars.debugWindow2x = args.isZoomed(); - if (args.isVerboseLoggingEnabled() || args.isDebugEnabled()) { + if (args.isVerboseLoggingEnabled() || args.isDebugEnabled()) StaticVars.outputLevel = ConsoleUtils.OUTPUTLEVEL_DEBUG_VERBOSE; - } Engine.platform.getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_MIN, args); checkDeviceType(); if (Engine.getPlatform().isRunningOnRaspberry() && args.isRaspberryModeAllowed()) { @@ -111,15 +111,15 @@ public class Engine { } public Observable getLoadPhase() { - return loadPhase; + return Engine.loadPhase; } - + public HardwareDevice getHardwareDevice() { return hardwareDevice; } - + public static Platform getPlatform() { - return platform; + return Engine.platform; } public static class LoadingStatus { diff --git a/core/src/main/java/it/cavallium/warppi/Platform.java b/core/src/main/java/it/cavallium/warppi/Platform.java index 8bad5737..592579f9 100644 --- a/core/src/main/java/it/cavallium/warppi/Platform.java +++ b/core/src/main/java/it/cavallium/warppi/Platform.java @@ -14,166 +14,189 @@ import it.cavallium.warppi.util.Error; public interface Platform { - public ConsoleUtils getConsoleUtils(); - public Gpio getGpio(); - public StorageUtils getStorageUtils(); - public PngUtils getPngUtils(); - public Settings getSettings(); + ConsoleUtils getConsoleUtils(); - public void setThreadName(Thread t, String name); - public void setThreadDaemon(Thread t); - public void setThreadDaemon(Thread t, boolean value); + Gpio getGpio(); - public void exit(int value); - public void gc(); + StorageUtils getStorageUtils(); - public boolean isJavascript(); - public boolean isRunningOnRaspberry(); - - public String getOsName(); + PngUtils getPngUtils(); - public void alphaChanged(boolean val); - public void shiftChanged(boolean val); + Settings getSettings(); - public Semaphore newSemaphore(); - public Semaphore newSemaphore(int i); - - public URLClassLoader newURLClassLoader(URL[] urls); + void setThreadName(Thread t, String name); - public Map getEnginesList(); - public GraphicEngine getEngine(String string) throws NullPointerException; + void setThreadDaemon(Thread t); - public void throwNewExceptionInInitializerError(String text); - public String[] stacktraceToString(Error e); + void setThreadDaemon(Thread t, boolean value); - public void loadPlatformRules(); - public void zip(String targetPath, String destinationFilePath, String password); - public void unzip(String targetZipFilePath, String destinationFolderPath, String password); + void exit(int value); - public boolean compile(String[] command, PrintWriter printWriter, PrintWriter errors); + void gc(); + + boolean isJavascript(); + + boolean isRunningOnRaspberry(); + + String getOsName(); + + void alphaChanged(boolean val); + + void shiftChanged(boolean val); + + Semaphore newSemaphore(); + + Semaphore newSemaphore(int i); + + URLClassLoader newURLClassLoader(URL[] urls); + + Map getEnginesList(); + + GraphicEngine getEngine(String string) throws NullPointerException; + + void throwNewExceptionInInitializerError(String text); + + String[] stacktraceToString(Error e); + + void loadPlatformRules(); + + void zip(String targetPath, String destinationFilePath, String password); + + void unzip(String targetZipFilePath, String destinationFolderPath, String password); + + boolean compile(String[] command, PrintWriter printWriter, PrintWriter errors); public interface Gpio { - public int valueOutput(); - public int valuePwmOutput(); - public int valueInput(); - public int valueHigh(); - public int valueLow(); - public Object valueUnknownBoardType(); + int valueOutput(); - public void wiringPiSetupPhys(); + int valuePwmOutput(); - public void pinMode(int i, int type); + int valueInput(); - public void digitalWrite(int pin, int val); + int valueHigh(); - public void digitalWrite(int pin, boolean val); + int valueLow(); - public void pwmWrite(int pin, int val); - - public void delayMicroseconds(int t); + Object valueUnknownBoardType(); - public int digitalRead(int pin); + void wiringPiSetupPhys(); - public Object getBoardType(); + void pinMode(int i, int type); + + void digitalWrite(int pin, int val); + + void digitalWrite(int pin, boolean val); + + void pwmWrite(int pin, int val); + + void delayMicroseconds(int t); + + int digitalRead(int pin); + + Object getBoardType(); } - + public interface ConsoleUtils { - public static final int OUTPUTLEVEL_NODEBUG = 0; - public static final int OUTPUTLEVEL_DEBUG_MIN = 1; - public static final int OUTPUTLEVEL_DEBUG_VERBOSE = 4; - - public AdvancedOutputStream out(); - - public int getOutputLevel(); - + int OUTPUTLEVEL_NODEBUG = 0; + int OUTPUTLEVEL_DEBUG_MIN = 1; + int OUTPUTLEVEL_DEBUG_VERBOSE = 4; + + AdvancedOutputStream out(); + + int getOutputLevel(); + public interface AdvancedOutputStream { - public void println(Object str); + void println(Object str); - public void println(int level); + void println(int level); - public void println(int level, Object str); + void println(int level, Object str); - public void print(int level, String str); + void print(int level, String str); - public void println(int level, String prefix, String str); + void println(int level, String prefix, String str); - public void println(int level, String... parts); + void println(int level, String... parts); } } - + public interface StorageUtils { int OpenOptionWrite = 0; int OpenOptionCreate = 1; - public boolean exists(File f); + boolean exists(File f); - public File get(String path); + File get(String path); - public File get(String... path); + File get(String... path); @Deprecated() - public File getResource(String string) throws IOException, URISyntaxException; + File getResource(String string) throws IOException, URISyntaxException; - public InputStream getResourceStream(String string) throws IOException, URISyntaxException; + InputStream getResourceStream(String string) throws IOException, URISyntaxException; - public List readAllLines(File file) throws IOException; - - public String read(InputStream input) throws IOException; + List readAllLines(File file) throws IOException; - public List walk(File dir) throws IOException; + String read(InputStream input) throws IOException; - public File relativize(File rulesPath, File f); + List walk(File dir) throws IOException; - public File resolve(File file, String string); - - public File getParent(File f); + File relativize(File rulesPath, File f); - public void createDirectories(File dir) throws IOException; + File resolve(File file, String string); - public void write(File f, byte[] bytes, int... options) throws IOException; + File getParent(File f); - public List readAllLines(InputStream input) throws IOException; + void createDirectories(File dir) throws IOException; - public String getBasePath(); + void write(File f, byte[] bytes, int... options) throws IOException; + + List readAllLines(InputStream input) throws IOException; + + String getBasePath(); } - + public interface Semaphore { void release(); + void acquire() throws InterruptedException; } - + public interface URLClassLoader { - public Class loadClass(String name) throws ClassNotFoundException; + Class loadClass(String name) throws ClassNotFoundException; + void close() throws IOException; } - + public interface PngUtils { - public PngReader load(InputStream resourceStream); - + PngReader load(InputStream resourceStream); + public interface PngReader { int[] getImageMatrix(); int[] getSize(); - + } - + } - + public interface Settings { - public boolean isDebugEnabled(); + boolean isDebugEnabled(); - public void setDebugEnabled(boolean debugOn); + void setDebugEnabled(boolean debugOn); - public default String getCalculatorName() { + default String getCalculatorName() { return "WarpPI"; } - public default String getCalculatorNameLowercase() { + + default String getCalculatorNameLowercase() { return "warppi"; } - public default String getCalculatorNameUppercase() { + + default String getCalculatorNameUppercase() { return "WARPPI"; } diff --git a/core/src/main/java/it/cavallium/warppi/StaticVars.java b/core/src/main/java/it/cavallium/warppi/StaticVars.java index 2ac86784..0e8a1b4a 100644 --- a/core/src/main/java/it/cavallium/warppi/StaticVars.java +++ b/core/src/main/java/it/cavallium/warppi/StaticVars.java @@ -17,13 +17,12 @@ public class StaticVars { public static boolean debugWindow2x = false; public static BehaviorSubject windowZoom = BehaviorSubject.create(2F); public static Function windowZoomFunction = (val) -> { - if (StaticVars.debugWindow2x) { + if (StaticVars.debugWindow2x) return val + 1; - } else { + else return val; - } }; - public static Observable windowZoom$ = windowZoom.map(windowZoomFunction); + public static Observable windowZoom$ = StaticVars.windowZoom.map(StaticVars.windowZoomFunction); public static StartupArguments startupArguments; private StaticVars() { diff --git a/core/src/main/java/it/cavallium/warppi/TestDrivers.java b/core/src/main/java/it/cavallium/warppi/TestDrivers.java index bc27a251..441dd2a2 100644 --- a/core/src/main/java/it/cavallium/warppi/TestDrivers.java +++ b/core/src/main/java/it/cavallium/warppi/TestDrivers.java @@ -1,25 +1,23 @@ package it.cavallium.warppi; public class TestDrivers { - public static void main(String[] args) { + public static void main(final String[] args) { System.out.println("Test started."); String className; className = "jogamp.newt.driver.bcm.vc.iv.DisplayDriver"; - if (exists(className)) { + if (TestDrivers.exists(className)) System.out.println("[FOUND] " + className); - } else { + else System.out.println("[NOT FOUND] " + className); - } className = ".bcm.vc.iv.DisplayDriver"; - if (exists(className)) { + if (TestDrivers.exists(className)) System.out.println("[FOUND] " + className); - } else { + else System.out.println("[NOT FOUND] " + className); - } System.out.println("Test finished."); } - public static boolean exists(String className) { + public static boolean exists(final String className) { try { Class.forName(className); return true; diff --git a/core/src/main/java/it/cavallium/warppi/boot/Boot.java b/core/src/main/java/it/cavallium/warppi/boot/Boot.java index d3ffaea2..329f1032 100644 --- a/core/src/main/java/it/cavallium/warppi/boot/Boot.java +++ b/core/src/main/java/it/cavallium/warppi/boot/Boot.java @@ -13,13 +13,13 @@ import it.cavallium.warppi.math.rules.RulesManager; import it.cavallium.warppi.util.Error; public class Boot { - - public static void boot(Platform platform, String[] args) throws Exception { - Engine.start(platform, new LoadingScreen(), new PIHardwareDisplay(), new PIHardwareTouchDevice(false, false, false), new CalculatorHUD(), parseStartupArguments(args)); + + public static void boot(final Platform platform, final String[] args) throws Exception { + Engine.start(platform, new LoadingScreen(), new PIHardwareDisplay(), new PIHardwareTouchDevice(false, false, false), new CalculatorHUD(), Boot.parseStartupArguments(args)); Engine.INSTANCE.getLoadPhase().subscribe(Boot::loadCalculator); } - private static void loadCalculator(LoadingStatus loading) { + private static void loadCalculator(final LoadingStatus loading) { try { Engine.INSTANCE.getHardwareDevice().getDisplayManager().setBrightness(0.2f); RulesManager.initialize(); @@ -33,12 +33,12 @@ public class Boot { public static StartupArguments parseStartupArguments(final String[] a) { final StartupArgumentsImpl args = new StartupArgumentsImpl(); - Arrays.asList(a).stream().parallel().map(String::toLowerCase).forEach(arg -> parseArgument(args, arg)); + Arrays.asList(a).stream().parallel().map(String::toLowerCase).forEach(arg -> Boot.parseArgument(args, arg)); args.setHeadlessEngineForced(args.isHeadlessEngineForced() || args.isHeadless8EngineForced() || args.isHeadless256EngineForced() || args.isHeadless24bitEngineForced()); return args; } - public static void parseArgument(StartupArgumentsImpl args, String arg) { + public static void parseArgument(final StartupArgumentsImpl args, final String arg) { switch (arg) { case "-zoomed": args.setZoomed(true); diff --git a/core/src/main/java/it/cavallium/warppi/boot/StartupArguments.java b/core/src/main/java/it/cavallium/warppi/boot/StartupArguments.java index 1f6928bc..9cbc7039 100644 --- a/core/src/main/java/it/cavallium/warppi/boot/StartupArguments.java +++ b/core/src/main/java/it/cavallium/warppi/boot/StartupArguments.java @@ -1,36 +1,36 @@ package it.cavallium.warppi.boot; public interface StartupArguments { - public boolean isRaspberryModeAllowed(); + boolean isRaspberryModeAllowed(); - public boolean isZoomed(); + boolean isZoomed(); - public boolean isHeadlessEngineForced(); + boolean isHeadlessEngineForced(); - public boolean isHeadless8EngineForced(); + boolean isHeadless8EngineForced(); - public boolean isHeadless256EngineForced(); + boolean isHeadless256EngineForced(); - public boolean isHeadless24bitEngineForced(); + boolean isHeadless24bitEngineForced(); - public boolean isCPUEngineForced(); + boolean isCPUEngineForced(); - public boolean isGPUEngineForced(); + boolean isGPUEngineForced(); - public boolean isFrameBufferEngineForced(); + boolean isFrameBufferEngineForced(); - public boolean isNoGUIEngineForced(); + boolean isNoGUIEngineForced(); - public boolean isHTMLEngineForced(); + boolean isHTMLEngineForced(); - public boolean isMSDOSModeEnabled(); + boolean isMSDOSModeEnabled(); - public boolean isVerboseLoggingEnabled(); + boolean isVerboseLoggingEnabled(); - public boolean isDebugEnabled(); + boolean isDebugEnabled(); - public boolean isUncached(); + boolean isUncached(); - public boolean isEngineForced(); + boolean isEngineForced(); } diff --git a/core/src/main/java/it/cavallium/warppi/boot/StartupArgumentsImpl.java b/core/src/main/java/it/cavallium/warppi/boot/StartupArgumentsImpl.java index 99f79928..f8feb508 100644 --- a/core/src/main/java/it/cavallium/warppi/boot/StartupArgumentsImpl.java +++ b/core/src/main/java/it/cavallium/warppi/boot/StartupArgumentsImpl.java @@ -102,63 +102,63 @@ public class StartupArgumentsImpl implements StartupArguments { return isCPUEngineForced || isFrameBufferEngineForced || isGPUEngineForced || isHeadless24bitEngineForced || isHeadless256EngineForced || isHeadless8EngineForced || isHTMLEngineForced || isNoGUIEngineForced; } - void setRaspberryModeAllowed(boolean isRaspberryModeAllowed) { + void setRaspberryModeAllowed(final boolean isRaspberryModeAllowed) { this.isRaspberryModeAllowed = isRaspberryModeAllowed; } - void setZoomed(boolean isZoomed) { + void setZoomed(final boolean isZoomed) { this.isZoomed = isZoomed; } - void setHeadlessEngineForced(boolean isHeadlessEngineForced) { + void setHeadlessEngineForced(final boolean isHeadlessEngineForced) { this.isHeadlessEngineForced = isHeadlessEngineForced; } - void setHeadless8EngineForced(boolean isHeadless8EngineForced) { + void setHeadless8EngineForced(final boolean isHeadless8EngineForced) { this.isHeadless8EngineForced = isHeadless8EngineForced; } - void setHeadless256EngineForced(boolean isHeadless256EngineForced) { + void setHeadless256EngineForced(final boolean isHeadless256EngineForced) { this.isHeadless256EngineForced = isHeadless256EngineForced; } - void setHeadless24bitEngineForced(boolean isHeadless24bitEngineForced) { + void setHeadless24bitEngineForced(final boolean isHeadless24bitEngineForced) { this.isHeadless24bitEngineForced = isHeadless24bitEngineForced; } - void setCPUEngineForced(boolean isCPUEngineForced) { + void setCPUEngineForced(final boolean isCPUEngineForced) { this.isCPUEngineForced = isCPUEngineForced; } - void setGPUEngineForced(boolean isGPUEngineForced) { + void setGPUEngineForced(final boolean isGPUEngineForced) { this.isGPUEngineForced = isGPUEngineForced; } - void setFrameBufferEngineForced(boolean isFrameBufferEngineForced) { + void setFrameBufferEngineForced(final boolean isFrameBufferEngineForced) { this.isFrameBufferEngineForced = isFrameBufferEngineForced; } - void setNoGUIEngineForced(boolean isNoGUIEngineForced) { + void setNoGUIEngineForced(final boolean isNoGUIEngineForced) { this.isNoGUIEngineForced = isNoGUIEngineForced; } - void setHTMLEngineForced(boolean isHTMLEngineForced) { + void setHTMLEngineForced(final boolean isHTMLEngineForced) { this.isHTMLEngineForced = isHTMLEngineForced; } - void setMSDOSModeEnabled(boolean isMSDOSModeEnabled) { + void setMSDOSModeEnabled(final boolean isMSDOSModeEnabled) { this.isMSDOSModeEnabled = isMSDOSModeEnabled; } - void setVerboseLoggingEnabled(boolean isVerboseLoggingEnabled) { + void setVerboseLoggingEnabled(final boolean isVerboseLoggingEnabled) { this.isVerboseLoggingEnabled = isVerboseLoggingEnabled; } - void setDebugEnabled(boolean isDebugEnabled) { + void setDebugEnabled(final boolean isDebugEnabled) { this.isDebugEnabled = isDebugEnabled; } - void setUncached(boolean isUncached) { + void setUncached(final boolean isUncached) { this.isUncached = isUncached; } diff --git a/core/src/main/java/it/cavallium/warppi/device/CacheFile.java b/core/src/main/java/it/cavallium/warppi/device/CacheFile.java index 48a5eb29..62c23b97 100644 --- a/core/src/main/java/it/cavallium/warppi/device/CacheFile.java +++ b/core/src/main/java/it/cavallium/warppi/device/CacheFile.java @@ -18,9 +18,9 @@ public class CacheFile { private FileInputStream lastFIS; public CacheFile() { - do { + do path = UUID.randomUUID().toString() + ".ser"; - } while (new File(path).exists()); + while (new File(path).exists()); try { File.createTempFile(Engine.getPlatform().getSettings().getCalculatorNameLowercase(), ""); } catch (final IOException e) { @@ -29,28 +29,26 @@ public class CacheFile { } public ObjectOutputStream getObjectOutputStram() { - if (lastOOS == null) { + if (lastOOS == null) try { return new ObjectOutputStream(new FileOutputStream(path)); } catch (final IOException e) { e.printStackTrace(); return lastOOS; } - } else { + else return lastOOS; - } } public ObjectInputStream getObjectInputStram() { - if (lastOIS == null) { + if (lastOIS == null) try { return new ObjectInputStream(new FileInputStream(path)); } catch (final IOException e) { return lastOIS; } - } else { + else return lastOIS; - } } public void closeStreams() { diff --git a/core/src/main/java/it/cavallium/warppi/device/HardwareDevice.java b/core/src/main/java/it/cavallium/warppi/device/HardwareDevice.java index 299a5f00..402060d8 100644 --- a/core/src/main/java/it/cavallium/warppi/device/HardwareDevice.java +++ b/core/src/main/java/it/cavallium/warppi/device/HardwareDevice.java @@ -7,7 +7,7 @@ public class HardwareDevice { private final DisplayManager displayManager; private final InputManager inputManager; - public HardwareDevice(DisplayManager m, InputManager im) { + public HardwareDevice(final DisplayManager m, final InputManager im) { displayManager = m; inputManager = im; } @@ -20,10 +20,10 @@ public class HardwareDevice { return inputManager; } - public void setup(Runnable r) { + public void setup(final Runnable r) { displayManager.initialize(); inputManager.getKeyboard().startKeyboard(); - Thread t = new Thread(r); + final Thread t = new Thread(r); Engine.getPlatform().setThreadDaemon(t, false); Engine.getPlatform().setThreadName(t, "Main thread (after setup)"); t.start(); diff --git a/core/src/main/java/it/cavallium/warppi/device/HardwareTouchDevice.java b/core/src/main/java/it/cavallium/warppi/device/HardwareTouchDevice.java index ce37c52c..5bf36efb 100644 --- a/core/src/main/java/it/cavallium/warppi/device/HardwareTouchDevice.java +++ b/core/src/main/java/it/cavallium/warppi/device/HardwareTouchDevice.java @@ -4,18 +4,18 @@ import it.cavallium.warppi.event.TouchEventListener; import it.cavallium.warppi.event.TouchPoint; public interface HardwareTouchDevice extends TouchEventListener { - public boolean getInvertedXY(); + boolean getInvertedXY(); - public boolean getInvertedX(); + boolean getInvertedX(); - public boolean getInvertedY(); + boolean getInvertedY(); - public default void setInvertedXY() {} + default void setInvertedXY() {} - public default void setInvertedX() {} + default void setInvertedX() {} - public default void setInvertedY() {} + default void setInvertedY() {} - public TouchPoint makePoint(long id, float x, float y, int maxX, int maxY, float radiusX, float radiusY, - float force, float rotationAngle); + TouchPoint makePoint(long id, float x, float y, int maxX, int maxY, float radiusX, float radiusY, float force, + float rotationAngle); } diff --git a/core/src/main/java/it/cavallium/warppi/device/InputManager.java b/core/src/main/java/it/cavallium/warppi/device/InputManager.java index 41f9cc0e..22e93090 100644 --- a/core/src/main/java/it/cavallium/warppi/device/InputManager.java +++ b/core/src/main/java/it/cavallium/warppi/device/InputManager.java @@ -4,9 +4,9 @@ public class InputManager { private final Keyboard keyboard; private final HardwareTouchDevice touchDevice; - public InputManager(Keyboard k, HardwareTouchDevice t) { - this.keyboard = k; - this.touchDevice = t; + public InputManager(final Keyboard k, final HardwareTouchDevice t) { + keyboard = k; + touchDevice = t; } public Keyboard getKeyboard() { diff --git a/core/src/main/java/it/cavallium/warppi/device/Keyboard.java b/core/src/main/java/it/cavallium/warppi/device/Keyboard.java index f6df9d0b..d9edafea 100644 --- a/core/src/main/java/it/cavallium/warppi/device/Keyboard.java +++ b/core/src/main/java/it/cavallium/warppi/device/Keyboard.java @@ -41,36 +41,36 @@ public class Keyboard { public synchronized void startKeyboard() { final Thread kt = new Thread(() -> { - if (Engine.getPlatform().getSettings().isDebugEnabled()) { + if (Engine.getPlatform().getSettings().isDebugEnabled()) try { while (true) { - if (debugKeyCode != -1) { - debugKeyPressed(debugKeyCode); - debugKeyCode = -1; + if (Keyboard.debugKeyCode != -1) { + Keyboard.debugKeyPressed(Keyboard.debugKeyCode); + Keyboard.debugKeyCode = -1; } - if (debugKeyCodeRelease != -1) { - debugKeyReleased(debugKeyCodeRelease); - debugKeyCodeRelease = -1; + if (Keyboard.debugKeyCodeRelease != -1) { + Keyboard.debugKeyReleased(Keyboard.debugKeyCodeRelease); + Keyboard.debugKeyCodeRelease = -1; } Thread.sleep(50); } } catch (final InterruptedException e) {} - } else { - Engine.getPlatform().getGpio().pinMode(CLK_INH_pin, Engine.getPlatform().getGpio().valueOutput()); - Engine.getPlatform().getGpio().pinMode(RCK_pin, Engine.getPlatform().getGpio().valueOutput()); - Engine.getPlatform().getGpio().pinMode(SER_pin, Engine.getPlatform().getGpio().valueOutput()); - Engine.getPlatform().getGpio().pinMode(SH_LD_pin, Engine.getPlatform().getGpio().valueOutput()); - Engine.getPlatform().getGpio().pinMode(SCK_and_CLK_pin, Engine.getPlatform().getGpio().valueOutput()); - Engine.getPlatform().getGpio().pinMode(QH_pin, Engine.getPlatform().getGpio().valueInput()); + else { + Engine.getPlatform().getGpio().pinMode(Keyboard.CLK_INH_pin, Engine.getPlatform().getGpio().valueOutput()); + Engine.getPlatform().getGpio().pinMode(Keyboard.RCK_pin, Engine.getPlatform().getGpio().valueOutput()); + Engine.getPlatform().getGpio().pinMode(Keyboard.SER_pin, Engine.getPlatform().getGpio().valueOutput()); + Engine.getPlatform().getGpio().pinMode(Keyboard.SH_LD_pin, Engine.getPlatform().getGpio().valueOutput()); + Engine.getPlatform().getGpio().pinMode(Keyboard.SCK_and_CLK_pin, Engine.getPlatform().getGpio().valueOutput()); + Engine.getPlatform().getGpio().pinMode(Keyboard.QH_pin, Engine.getPlatform().getGpio().valueInput()); - Engine.getPlatform().getGpio().digitalWrite(CLK_INH_pin, false); - Engine.getPlatform().getGpio().digitalWrite(RCK_pin, false); - Engine.getPlatform().getGpio().digitalWrite(SER_pin, false); - Engine.getPlatform().getGpio().digitalWrite(SH_LD_pin, false); - Engine.getPlatform().getGpio().digitalWrite(SCK_and_CLK_pin, false); - Engine.getPlatform().getGpio().digitalWrite(QH_pin, false); - final SerialToParallel chip1 = new SerialToParallel(RCK_pin, SCK_and_CLK_pin /*SCK*/, SER_pin); - final ParallelToSerial chip2 = new ParallelToSerial(SH_LD_pin, CLK_INH_pin, QH_pin, SCK_and_CLK_pin/*CLK*/); + Engine.getPlatform().getGpio().digitalWrite(Keyboard.CLK_INH_pin, false); + Engine.getPlatform().getGpio().digitalWrite(Keyboard.RCK_pin, false); + Engine.getPlatform().getGpio().digitalWrite(Keyboard.SER_pin, false); + Engine.getPlatform().getGpio().digitalWrite(Keyboard.SH_LD_pin, false); + Engine.getPlatform().getGpio().digitalWrite(Keyboard.SCK_and_CLK_pin, false); + Engine.getPlatform().getGpio().digitalWrite(Keyboard.QH_pin, false); + final SerialToParallel chip1 = new SerialToParallel(Keyboard.RCK_pin, Keyboard.SCK_and_CLK_pin /*SCK*/, Keyboard.SER_pin); + final ParallelToSerial chip2 = new ParallelToSerial(Keyboard.SH_LD_pin, Keyboard.CLK_INH_pin, Keyboard.QH_pin, Keyboard.SCK_and_CLK_pin/*CLK*/); KeyboardDebugScreen.log("Started keyboard system"); @@ -85,15 +85,14 @@ public class Keyboard { // KeyboardDebugScreen.ks[col] = data; for (int row = 0; row < 8; row++) { - if (data[row] == true && precedentStates[row][col] == false) { -// System.out.println("Pressed button at " + (row + 1) + ", " + (col + 1)); + if (data[row] == true && Keyboard.precedentStates[row][col] == false) + // System.out.println("Pressed button at " + (row + 1) + ", " + (col + 1)); // KeyboardDebugScreen.log("Pressed button at " + (row + 1) + ", " + (col + 1)); - keyPressedRaw(row, col); - } else if (data[row] == false && precedentStates[row][col] == true) { - keyReleasedRaw(row, col); + Keyboard.keyPressedRaw(row, col); + else if (data[row] == false && Keyboard.precedentStates[row][col] == true) + Keyboard.keyReleasedRaw(row, col); // KeyboardDebugScreen.log("Released button at " + (row + 1) + ", " + (col + 1)); - } - precedentStates[row][col] = data[row]; + Keyboard.precedentStates[row][col] = data[row]; } } } @@ -105,259 +104,229 @@ public class Keyboard { kt.start(); } - public static void debugKeyPressed(int keyCode) { + public static void debugKeyPressed(final int keyCode) { switch (keyCode) { case KeyEvent.VK_ESCAPE: Keyboard.keyPressed(Key.POWEROFF); break; case KeyEvent.VK_S: - if (Keyboard.shift) { + if (Keyboard.shift) Keyboard.keyPressed(Key.ARCSINE); - } else if (Keyboard.alpha) { + else if (Keyboard.alpha) Keyboard.keyPressed(Key.LETTER_S); - } else { + else Keyboard.keyPressed(Key.SINE); - } break; case KeyEvent.VK_C: - if (Keyboard.shift) { + if (Keyboard.shift) Keyboard.keyPressed(Key.ARCCOSINE); - } else if (Keyboard.alpha) { + else if (Keyboard.alpha) Keyboard.keyPressed(Key.LETTER_C); - } else { + else Keyboard.keyPressed(Key.COSINE); - } break; case KeyEvent.VK_T: - if (Keyboard.shift) { + if (Keyboard.shift) Keyboard.keyPressed(Key.ARCTANGENT); - } else if (Keyboard.alpha) { + else if (Keyboard.alpha) Keyboard.keyPressed(Key.LETTER_T); - } else { + else Keyboard.keyPressed(Key.TANGENT); - } break; case KeyEvent.VK_D: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.debug_DEG); - } else if (Keyboard.alpha) { + else if (Keyboard.alpha) Keyboard.keyPressed(Key.LETTER_D); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_R: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.debug_RAD); - } else if (Keyboard.alpha) { + else if (Keyboard.alpha) Keyboard.keyPressed(Key.LETTER_R); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_G: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.debug_GRA); - } else if (Keyboard.alpha) { + else if (Keyboard.alpha) Keyboard.keyPressed(Key.LETTER_G); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_X: - if (Keyboard.alpha) { + if (Keyboard.alpha) Keyboard.keyPressed(Key.LETTER_X); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_P: - if (Keyboard.shift) { + if (Keyboard.shift) Keyboard.keyPressed(Key.NONE); - } else if (Keyboard.alpha) { + else if (Keyboard.alpha) Keyboard.keyPressed(Key.LETTER_P); - } else { + else Keyboard.keyPressed(Key.PI); - } break; case KeyEvent.VK_E: - if (Keyboard.shift) { + if (Keyboard.shift) Keyboard.keyPressed(Key.NONE); - } else if (Keyboard.alpha) { + else if (Keyboard.alpha) Keyboard.keyPressed(Key.LETTER_E); - } else { + else Keyboard.keyPressed(Key.EULER_NUMBER); - } break; case KeyEvent.VK_Y: - if (Keyboard.alpha) { + if (Keyboard.alpha) Keyboard.keyPressed(Key.LETTER_Y); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_B: - if (Keyboard.shift) { + if (Keyboard.shift) Keyboard.keyPressed(Key.BRIGHTNESS_CYCLE_REVERSE); - } else if (!Keyboard.shift && !Keyboard.alpha) { + else if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.BRIGHTNESS_CYCLE); - } else { + else Keyboard.keyPressed(Key.LETTER_B); - } break; case KeyEvent.VK_L: - if (Keyboard.shift) { + if (Keyboard.shift) Keyboard.keyPressed(Key.LOGARITHM); - } else if (Keyboard.alpha) { + else if (Keyboard.alpha) Keyboard.keyPressed(Key.LETTER_L); - } else { + else Keyboard.keyPressed(Key.LOGARITHM); - } break; case KeyboardJogampValues.VK_ENTER: case KeyEvent.VK_ENTER: - if (Keyboard.shift) { + if (Keyboard.shift) Keyboard.keyPressed(Key.STEP); - } else if (!Keyboard.shift && !Keyboard.alpha) { + else if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.SIMPLIFY); - } else { + else Keyboard.keyPressed(Key.NONE); - } int row = 2; int col = 1; Keyboard.debugKeysDown[row - 1][col - 1] = true; break; case KeyEvent.VK_1: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NUM1); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_2: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NUM2); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_3: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NUM3); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_4: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NUM4); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_5: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NUM5); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_6: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NUM6); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_7: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NUM7); - } else if (Keyboard.shift) { - if (Engine.getPlatform().getSettings().isDebugEnabled()) { + else if (Keyboard.shift) + if (Engine.getPlatform().getSettings().isDebugEnabled()) Keyboard.keyPressed(Key.DIVIDE); - } - } break; case KeyEvent.VK_8: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NUM8); - } else if (Keyboard.shift) { + else if (Keyboard.shift) Keyboard.keyPressed(Key.PARENTHESIS_OPEN); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_9: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NUM9); - } else if (Keyboard.shift) { + else if (Keyboard.shift) Keyboard.keyPressed(Key.PARENTHESIS_CLOSE); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_0: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NUM0); - } else if (Keyboard.shift) { + else if (Keyboard.shift) Keyboard.keyPressed(Key.EQUAL); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_M: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.SURD_MODE); - } else if (Keyboard.shift) { + else if (Keyboard.shift) Keyboard.keyPressed(Key.NONE); - } else { + else Keyboard.keyPressed(Key.LETTER_M); - } break; case KeyboardJogampValues.VK_ADD: case KeyEvent.VK_ADD: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.PLUS); - } else if (Keyboard.shift) { + else if (Keyboard.shift) Keyboard.keyPressed(Key.PLUS_MINUS); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyboardJogampValues.VK_SUBTRACT: case KeyEvent.VK_SUBTRACT: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.MINUS); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyboardJogampValues.VK_MULTIPLY: case KeyEvent.VK_MULTIPLY: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.MULTIPLY); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyboardJogampValues.VK_DIVIDE: case KeyEvent.VK_DIVIDE: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.DIVIDE); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_BACK_SPACE: Keyboard.keyPressed(Key.DELETE); break; case KeyboardJogampValues.VK_DELETE: case KeyEvent.VK_DELETE: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.RESET); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyboardJogampValues.VK_LEFT: case KeyEvent.VK_LEFT: @@ -365,11 +334,10 @@ public class Keyboard { row = 2; col = 3; Keyboard.debugKeysDown[row - 1][col - 1] = true; - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.LEFT); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyboardJogampValues.VK_RIGHT: case KeyEvent.VK_RIGHT: @@ -377,11 +345,10 @@ public class Keyboard { row = 2; col = 5; Keyboard.debugKeysDown[row - 1][col - 1] = true; - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.RIGHT); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyboardJogampValues.VK_UP: case KeyEvent.VK_UP: @@ -389,11 +356,10 @@ public class Keyboard { row = 1; col = 4; Keyboard.debugKeysDown[row - 1][col - 1] = true; - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.UP); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyboardJogampValues.VK_DOWN: case KeyEvent.VK_DOWN: @@ -401,188 +367,170 @@ public class Keyboard { row = 3; col = 4; Keyboard.debugKeysDown[row - 1][col - 1] = true; - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.DOWN); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case (short) 12: //DOWN row = 2; col = 4; Keyboard.debugKeysDown[row - 1][col - 1] = true; - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.OK); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyboardJogampValues.VK_NUMPAD4: case KeyEvent.VK_NUMPAD4: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.HISTORY_BACK); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyboardJogampValues.VK_NUMPAD6: case KeyEvent.VK_NUMPAD6: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.HISTORY_FORWARD); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_PERIOD: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.DOT); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_A: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else if (Keyboard.alpha && !Keyboard.shift) { + else if (Keyboard.alpha && !Keyboard.shift) Keyboard.keyPressed(Key.LETTER_A); - } else if (Keyboard.shift && !Keyboard.alpha) { + else if (Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_F: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else if (Keyboard.alpha && !Keyboard.shift) { + else if (Keyboard.alpha && !Keyboard.shift) Keyboard.keyPressed(Key.LETTER_F); - } else if (Keyboard.shift && !Keyboard.alpha) { + else if (Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_H: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else if (Keyboard.alpha && !Keyboard.shift) { + else if (Keyboard.alpha && !Keyboard.shift) Keyboard.keyPressed(Key.LETTER_H); - } else if (Keyboard.shift && !Keyboard.alpha) { + else if (Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_I: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else if (Keyboard.alpha && !Keyboard.shift) { + else if (Keyboard.alpha && !Keyboard.shift) Keyboard.keyPressed(Key.LETTER_I); - } else if (Keyboard.shift && !Keyboard.alpha) { + else if (Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_J: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else if (Keyboard.alpha && !Keyboard.shift) { + else if (Keyboard.alpha && !Keyboard.shift) Keyboard.keyPressed(Key.LETTER_J); - } else if (Keyboard.shift && !Keyboard.alpha) { + else if (Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_K: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else if (Keyboard.alpha && !Keyboard.shift) { + else if (Keyboard.alpha && !Keyboard.shift) Keyboard.keyPressed(Key.LETTER_K); - } else if (Keyboard.shift && !Keyboard.alpha) { + else if (Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_N: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else if (Keyboard.alpha && !Keyboard.shift) { + else if (Keyboard.alpha && !Keyboard.shift) Keyboard.keyPressed(Key.LETTER_N); - } else if (Keyboard.shift && !Keyboard.alpha) { + else if (Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_O: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else if (Keyboard.alpha && !Keyboard.shift) { + else if (Keyboard.alpha && !Keyboard.shift) Keyboard.keyPressed(Key.LETTER_O); - } else if (Keyboard.shift && !Keyboard.alpha) { + else if (Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_Q: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else if (Keyboard.alpha && !Keyboard.shift) { + else if (Keyboard.alpha && !Keyboard.shift) Keyboard.keyPressed(Key.LETTER_Q); - } else if (Keyboard.shift && !Keyboard.alpha) { + else if (Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_U: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else if (Keyboard.alpha && !Keyboard.shift) { + else if (Keyboard.alpha && !Keyboard.shift) Keyboard.keyPressed(Key.LETTER_U); - } else if (Keyboard.shift && !Keyboard.alpha) { + else if (Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_V: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else if (Keyboard.alpha && !Keyboard.shift) { + else if (Keyboard.alpha && !Keyboard.shift) Keyboard.keyPressed(Key.LETTER_V); - } else if (Keyboard.shift && !Keyboard.alpha) { + else if (Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_W: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else if (Keyboard.alpha && !Keyboard.shift) { + else if (Keyboard.alpha && !Keyboard.shift) Keyboard.keyPressed(Key.LETTER_W); - } else if (Keyboard.shift && !Keyboard.alpha) { + else if (Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyEvent.VK_Z: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.NONE); - } else if (Keyboard.alpha && !Keyboard.shift) { + else if (Keyboard.alpha && !Keyboard.shift) Keyboard.keyPressed(Key.LETTER_Z); - } else if (Keyboard.shift && !Keyboard.alpha) { + else if (Keyboard.shift && !Keyboard.alpha) Keyboard.keyPressed(Key.ZOOM_MODE); - } else { + else Keyboard.keyPressed(Key.NONE); - } break; case KeyboardJogampValues.VK_SHIFT: case KeyEvent.VK_SHIFT: @@ -610,7 +558,7 @@ public class Keyboard { } } - private synchronized static void debugKeyReleased(int keyCode) { + private synchronized static void debugKeyReleased(final int keyCode) { switch (keyCode) { case KeyEvent.VK_ENTER: int row = 2; @@ -655,15 +603,14 @@ public class Keyboard { } } - public static boolean isKeyDown(int row, int col) { - if (Engine.getPlatform().getSettings().isDebugEnabled() == false) { - return precedentStates[row - 1][col - 1]; - } else { - return debugKeysDown[row - 1][col - 1]; - } + public static boolean isKeyDown(final int row, final int col) { + if (Engine.getPlatform().getSettings().isDebugEnabled() == false) + return Keyboard.precedentStates[row - 1][col - 1]; + else + return Keyboard.debugKeysDown[row - 1][col - 1]; } - public synchronized static void keyReleasedRaw(int row, int col) { + public synchronized static void keyReleasedRaw(final int row, final int col) { // KeyboardDebugScreen.keyX = row; // KeyboardDebugScreen.keyY = col; if (row == 1 && col == 1) { @@ -672,80 +619,80 @@ public class Keyboard { } static final String[][][] KeyLabelsMap = /* [ROW, COLUMN, (0:normal 1:shift 2:alpha)] */ - { { /* ROW 0 */ - { "⇪", "⇪", null }, /* 0,0 */ - { "A", null, "A" }, /* 0,1 */ - {"", null, null }, /* 0,2 */ - { "⇧", null, null }, /* 0,3 */ - {"", null, null }, /* 0,4 */ - {"", null, null }, /* 0,5 */ - { "☼", "☼", null }, /* 0,6 */ - {"↩", null, null } /* 0,7 */ - }, { /* ROW 1 */ - {"", null, null }, /* 1,0 */ - {"", null, null }, /* 1,1 */ - {"⇦", null, null }, /* 1,2 */ - {"OK", null, null }, /* 1,3 */ - {"⇨", null, null }, /* 1,4 */ - {"↤", null, null }, /* 1,5 */ - {"↦", null, null }, /* 1,6 */ - {"", null, null } /* 1,7 */ - }, { /* ROW 2 */ - {"", null, null }, /* 2,0 */ - {"√", null, null }, /* 2,1 */ - {"", null, null }, /* 2,2 */ - {"⇩", null, null }, /* 2,3 */ - {"↶", null, null }, /* 2,4 */ - {"", null, null }, /* 2,5 */ - {"", null, null }, /* 2,6 */ - {"", null, null } /* 2,7 */ - }, { /* ROW 3 */ - {"", null, null }, /* 3,0 */ - {"", null, null }, /* 3,1 */ - {"^x", null, null }, /* 3,2 */ - {"^2", null, null }, /* 3,3 */ - {"", null, null }, /* 3,4 */ - {"", null, null }, /* 3,5 */ - {"", null, null }, /* 3,6 */ - {".", null, "y" } /* 3,7 */ - }, { /* ROW 4 */ - {"", null, null }, /* 4,0 */ - {"", null, null }, /* 4,1 */ - {"(", null, null }, /* 4,2 */ - {")", null, null }, /* 4,3 */ - {"", null, null }, /* 4,4 */ - {"S⇔D", null, null }, /* 4,5 */ - {"", null, null }, /* 4,6 */ - {"0", null, "x" } /* 4,7 */ - }, { /* ROW 5 */ - {"7", null, null }, /* 5,0 */ - {"8", null, null }, /* 5,1 */ - {"9", null, null }, /* 5,2 */ - {"⌫", null, null }, /* 5,3 */ - {"RESET", null, null }, /* 5,4 */ - {"", null, null }, /* 5,5 */ - {"", null, null }, /* 5,6 */ - {"", null, null } /* 5,7 */ - }, { /* ROW 6 */ - {"4", null, null }, /* 6,0 */ - {"5", null, null }, /* 6,1 */ - {"6", null, null }, /* 6,2 */ - {"*", null, null }, /* 6,3 */ - {"/", null, null }, /* 6,4 */ - {"", null, null }, /* 6,5 */ - {"", null, null }, /* 6,6 */ - {"", null, null } /* 6,7 */ - }, { /* ROW 7 */ - {"1", null, null }, /* 7,0 */ - {"2", null, null }, /* 7,1 */ - {"3", null, null }, /* 7,2 */ - {"+", null, null }, /* 7,3 */ - {"-", null, null }, /* 7,4 */ - {"", null, null }, /* 7,5 */ - {"", null, null }, /* 7,6 */ - {"", null, null } /* 7,7 */ - } }; - + { { /* ROW 0 */ + { "⇪", "⇪", null }, /* 0,0 */ + { "A", null, "A" }, /* 0,1 */ + { "", null, null }, /* 0,2 */ + { "⇧", null, null }, /* 0,3 */ + { "", null, null }, /* 0,4 */ + { "", null, null }, /* 0,5 */ + { "☼", "☼", null }, /* 0,6 */ + { "↩", null, null } /* 0,7 */ + }, { /* ROW 1 */ + { "", null, null }, /* 1,0 */ + { "", null, null }, /* 1,1 */ + { "⇦", null, null }, /* 1,2 */ + { "OK", null, null }, /* 1,3 */ + { "⇨", null, null }, /* 1,4 */ + { "↤", null, null }, /* 1,5 */ + { "↦", null, null }, /* 1,6 */ + { "", null, null } /* 1,7 */ + }, { /* ROW 2 */ + { "", null, null }, /* 2,0 */ + { "√", null, null }, /* 2,1 */ + { "", null, null }, /* 2,2 */ + { "⇩", null, null }, /* 2,3 */ + { "↶", null, null }, /* 2,4 */ + { "", null, null }, /* 2,5 */ + { "", null, null }, /* 2,6 */ + { "", null, null } /* 2,7 */ + }, { /* ROW 3 */ + { "", null, null }, /* 3,0 */ + { "", null, null }, /* 3,1 */ + { "^x", null, null }, /* 3,2 */ + { "^2", null, null }, /* 3,3 */ + { "", null, null }, /* 3,4 */ + { "", null, null }, /* 3,5 */ + { "", null, null }, /* 3,6 */ + { ".", null, "y" } /* 3,7 */ + }, { /* ROW 4 */ + { "", null, null }, /* 4,0 */ + { "", null, null }, /* 4,1 */ + { "(", null, null }, /* 4,2 */ + { ")", null, null }, /* 4,3 */ + { "", null, null }, /* 4,4 */ + { "S⇔D", null, null }, /* 4,5 */ + { "", null, null }, /* 4,6 */ + { "0", null, "x" } /* 4,7 */ + }, { /* ROW 5 */ + { "7", null, null }, /* 5,0 */ + { "8", null, null }, /* 5,1 */ + { "9", null, null }, /* 5,2 */ + { "⌫", null, null }, /* 5,3 */ + { "RESET", null, null }, /* 5,4 */ + { "", null, null }, /* 5,5 */ + { "", null, null }, /* 5,6 */ + { "", null, null } /* 5,7 */ + }, { /* ROW 6 */ + { "4", null, null }, /* 6,0 */ + { "5", null, null }, /* 6,1 */ + { "6", null, null }, /* 6,2 */ + { "*", null, null }, /* 6,3 */ + { "/", null, null }, /* 6,4 */ + { "", null, null }, /* 6,5 */ + { "", null, null }, /* 6,6 */ + { "", null, null } /* 6,7 */ + }, { /* ROW 7 */ + { "1", null, null }, /* 7,0 */ + { "2", null, null }, /* 7,1 */ + { "3", null, null }, /* 7,2 */ + { "+", null, null }, /* 7,3 */ + { "-", null, null }, /* 7,4 */ + { "", null, null }, /* 7,5 */ + { "", null, null }, /* 7,6 */ + { "", null, null } /* 7,7 */ + } }; + static final Key[][][] keyMap = /* [ROW, COLUMN, (0:normal 1:shift 2:alpha)] */ { { /* ROW 0 */ { Key.SHIFT, Key.SHIFT, Key.SHIFT }, /* 0,0 */ @@ -820,45 +767,40 @@ public class Keyboard { { Key.NONE, Key.NONE, Key.NONE }, /* 7,6 */ { Key.NONE, Key.NONE, Key.NONE } /* 7,7 */ } }; - - public static String getKeyName(int row, int col) { - return getKeyName(row, col, shift, alpha); + + public static String getKeyName(final int row, final int col) { + return Keyboard.getKeyName(row, col, Keyboard.shift, Keyboard.alpha); } - - public static String getKeyName(int row, int col, boolean shift, boolean alpha) { - String[] keyValues = KeyLabelsMap[row][col]; + + public static String getKeyName(final int row, final int col, final boolean shift, final boolean alpha) { + final String[] keyValues = Keyboard.KeyLabelsMap[row][col]; if (shift) { - if (keyValues[1] != null) { + if (keyValues[1] != null) return keyValues[1]; - } - } else if (alpha) { - if (keyValues[2] != null) { + } else if (alpha) + if (keyValues[2] != null) return keyValues[2]; - } - } return keyValues[0]; } - public static boolean hasKeyName(int row, int col) { - String[] keyValues = KeyLabelsMap[row][col]; - if (shift) { + public static boolean hasKeyName(final int row, final int col) { + final String[] keyValues = Keyboard.KeyLabelsMap[row][col]; + if (Keyboard.shift) return keyValues[1] != null; - } else if (alpha) { + else if (Keyboard.alpha) return keyValues[2] != null; - } else { + else return true; - } } - public static synchronized void keyPressedRaw(int row, int col) { + public static synchronized void keyPressedRaw(final int row, final int col) { // KeyboardDebugScreen.keyX = row; // KeyboardDebugScreen.keyY = col; - final Key k = keyMap[row][col][shift ? 1 : alpha ? 2 : 0]; - if (k != null) { - keyPressed(k); - } else { - keyPressed(Key.NONE); - } + final Key k = Keyboard.keyMap[row][col][Keyboard.shift ? 1 : Keyboard.alpha ? 2 : 0]; + if (k != null) + Keyboard.keyPressed(k); + else + Keyboard.keyPressed(Key.NONE); } public static void stopKeyboard() { @@ -872,15 +814,14 @@ public class Keyboard { } } - public synchronized static void keyPressed(Key k) { + public synchronized static void keyPressed(final Key k) { boolean done = false; - if (additionalListener != null) { + if (Keyboard.additionalListener != null) try { - done = additionalListener.onKeyPressed(new KeyPressedEvent(k)); + done = Keyboard.additionalListener.onKeyPressed(new KeyPressedEvent(k)); } catch (final Exception ex) { new GUIErrorMessage(ex); } - } if (Engine.INSTANCE.getHardwareDevice().getDisplayManager() != null) { final Screen scr = Engine.INSTANCE.getHardwareDevice().getDisplayManager().getScreen(); boolean refresh = false; @@ -890,9 +831,9 @@ public class Keyboard { } catch (final Exception ex) { new GUIErrorMessage(ex); } - if (scr != null && scr.initialized && scrdone) { + if (scr != null && scr.initialized && scrdone) refresh = true; - } else { + else switch (k) { case POWEROFF: Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.destroy(); @@ -909,7 +850,7 @@ public class Keyboard { refresh = true; break; case ZOOM_MODE: - float newZoom = (StaticVars.windowZoom.getLastValue() % 3) + 1; + final float newZoom = StaticVars.windowZoom.getLastValue() % 3 + 1; StaticVars.windowZoom.onNext(newZoom); Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_MIN, "Keyboard", "Zoom: " + newZoom); // StaticVars.windowZoom = ((StaticVars.windowZoom - 0.5f) % 2f) + 1f; @@ -925,7 +866,6 @@ public class Keyboard { default: break; } - } switch (k) { case SHIFT: if (Keyboard.alpha) @@ -948,47 +888,41 @@ public class Keyboard { } break; } - if (refresh) { - refreshRequest = true; - } - } else if (!done) { + if (refresh) + Keyboard.refreshRequest = true; + } else if (!done) Engine.getPlatform().getConsoleUtils().out().println(1, "Key " + k.toString() + " ignored."); - } } - public synchronized static void keyReleased(Key k) { + public synchronized static void keyReleased(final Key k) { boolean done = false; - if (additionalListener != null) { - done = additionalListener.onKeyReleased(new KeyReleasedEvent(k)); - } + if (Keyboard.additionalListener != null) + done = Keyboard.additionalListener.onKeyReleased(new KeyReleasedEvent(k)); boolean refresh = false; if (Engine.INSTANCE.getHardwareDevice().getDisplayManager() != null) { final Screen scr = Engine.INSTANCE.getHardwareDevice().getDisplayManager().getScreen(); - if (scr != null && scr.initialized && scr.onKeyReleased(new KeyReleasedEvent(k))) { + if (scr != null && scr.initialized && scr.onKeyReleased(new KeyReleasedEvent(k))) refresh = true; - } else { + else switch (k) { case NONE: break; default: break; } - } - if (refresh) { - refreshRequest = true; - } - } else if (!done) { + if (refresh) + Keyboard.refreshRequest = true; + } else if (!done) Engine.getPlatform().getConsoleUtils().out().println(1, "Key " + k.toString() + " ignored."); - } } - public void setAdditionalKeyboardListener(KeyboardEventListener l) { - additionalListener = l; + public void setAdditionalKeyboardListener(final KeyboardEventListener l) { + Keyboard.additionalListener = l; } public static boolean popRefreshRequest() { - if (refreshRequest) { - refreshRequest = false; + if (Keyboard.refreshRequest) { + Keyboard.refreshRequest = false; return true; } return false; @@ -1007,7 +941,7 @@ Keyboard: | SHIFT STATE | | ALPHA STATE | |--------------| - + Physical keyboard: |0,0-----|0,1-----|########|0,3-----|########|0,5-----|0,6-----| | SHIFT | ALPHA |########| ^ |########|SETTINGS|+BRIGHT | @@ -1050,28 +984,28 @@ Keyboard: SCREEN F_n: MathInputScreen: Default: - [F_1] Normal: Solve for X Shift: Solve for _ Alpha: - [F_2] Normal: Shift: Alpha: - [F_3] Normal: Variables & constants Shift: Alpha: - [F_4] Normal: Functions f(x) Shift: Alpha: + [F_1] Normal: Solve for X Shift: Solve for _ Alpha: + [F_2] Normal: Shift: Alpha: + [F_3] Normal: Variables & constants Shift: Alpha: + [F_4] Normal: Functions f(x) Shift: Alpha: Variable popup: - [F_1] Normal(if constant):Set value Shift: Alpha: - [F_2] Normal: Shift: Alpha: - [F_3] Normal: Shift: Alpha: - [F_4] Normal: Shift: Alpha: + [F_1] Normal(if constant):Set value Shift: Alpha: + [F_2] Normal: Shift: Alpha: + [F_3] Normal: Shift: Alpha: + [F_4] Normal: Shift: Alpha: MarioScreen - [F_1] Normal: Shift: Alpha: - [F_2] Normal: Shift: Alpha: - [F_3] Normal: Shift: Alpha: - [F_4] Normal: Shift: Alpha: + [F_1] Normal: Shift: Alpha: + [F_2] Normal: Shift: Alpha: + [F_3] Normal: Shift: Alpha: + [F_4] Normal: Shift: Alpha: ChooseVariableValueScreen - [F_1] Normal: Shift: Alpha: - [F_2] Normal: Shift: Alpha: - [F_3] Normal: Shift: Alpha: - [F_4] Normal: Shift: Alpha: + [F_1] Normal: Shift: Alpha: + [F_2] Normal: Shift: Alpha: + [F_3] Normal: Shift: Alpha: + [F_4] Normal: Shift: Alpha: SolveForXScreen - [F_1] Normal: Shift: Alpha: - [F_2] Normal: Shift: Alpha: - [F_3] Normal: Shift: Alpha: - [F_4] Normal: Shift: Alpha: + [F_1] Normal: Shift: Alpha: + [F_2] Normal: Shift: Alpha: + [F_3] Normal: Shift: Alpha: + [F_4] Normal: Shift: Alpha: */ \ No newline at end of file diff --git a/core/src/main/java/it/cavallium/warppi/device/KeyboardJogampValues.java b/core/src/main/java/it/cavallium/warppi/device/KeyboardJogampValues.java index 7a59f6f7..1cfe22e3 100644 --- a/core/src/main/java/it/cavallium/warppi/device/KeyboardJogampValues.java +++ b/core/src/main/java/it/cavallium/warppi/device/KeyboardJogampValues.java @@ -9,108 +9,108 @@ public interface KeyboardJogampValues { /** * This value, {@value}, is used to indicate that the keyCode is unknown. */ - public static final short VK_UNDEFINED = (short) 0x0; + short VK_UNDEFINED = (short) 0x0; - static final short VK_FREE01 = (short) 0x01; + short VK_FREE01 = (short) 0x01; /** Constant for the HOME function key. ASCII: Start Of Text. */ - public static final short VK_HOME = (short) 0x02; + short VK_HOME = (short) 0x02; /** Constant for the END function key. ASCII: End Of Text. */ - public static final short VK_END = (short) 0x03; + short VK_END = (short) 0x03; /** Constant for the END function key. ASCII: End Of Transmission. */ - public static final short VK_FINAL = (short) 0x04; + short VK_FINAL = (short) 0x04; /** Constant for the PRINT function key. ASCII: Enquiry. */ - public static final short VK_PRINTSCREEN = (short) 0x05; + short VK_PRINTSCREEN = (short) 0x05; - static final short VK_FREE06 = (short) 0x06; - static final short VK_FREE07 = (short) 0x07; + short VK_FREE06 = (short) 0x06; + short VK_FREE07 = (short) 0x07; /** Constant for the BACK SPACE key "\b", matching ASCII. Printable! */ - public static final short VK_BACK_SPACE = (short) 0x08; + short VK_BACK_SPACE = (short) 0x08; /** Constant for the HORIZ TAB key "\t", matching ASCII. Printable! */ - public static final short VK_TAB = (short) 0x09; + short VK_TAB = (short) 0x09; /** LINE_FEED "\n", matching ASCII, n/a on keyboard. */ - static final short VK_FREE0A = (short) 0x0A; + short VK_FREE0A = (short) 0x0A; /** Constant for the PAGE DOWN function key. ASCII: Vertical Tabulation. */ - public static final short VK_PAGE_DOWN = (short) 0x0B; + short VK_PAGE_DOWN = (short) 0x0B; /** Constant for the CLEAR key, i.e. FORM FEED, matching ASCII. */ - public static final short VK_CLEAR = (short) 0x0C; + short VK_CLEAR = (short) 0x0C; /** * Constant for the ENTER key, i.e. CARRIAGE RETURN, matching ASCII. * Printable! */ - public static final short VK_ENTER = (short) 0x0D; + short VK_ENTER = (short) 0x0D; - static final short VK_FREE0E = (short) 0x0E; + short VK_FREE0E = (short) 0x0E; /** Constant for the CTRL function key. ASCII: shift-in. */ - public static final short VK_SHIFT = (short) 0x0F; + short VK_SHIFT = (short) 0x0F; /** Constant for the PAGE UP function key. ASCII: Data Link Escape. */ - public static final short VK_PAGE_UP = (short) 0x10; + short VK_PAGE_UP = (short) 0x10; /** Constant for the CTRL function key. ASCII: device-ctrl-one. */ - public static final short VK_CONTROL = (short) 0x11; + short VK_CONTROL = (short) 0x11; /** Constant for the left ALT function key. ASCII: device-ctrl-two. */ - public static final short VK_ALT = (short) 0x12; + short VK_ALT = (short) 0x12; /** * Constant for the ALT_GRAPH function key, i.e. right ALT key. ASCII: * device-ctrl-three. */ - public static final short VK_ALT_GRAPH = (short) 0x13; + short VK_ALT_GRAPH = (short) 0x13; /** Constant for the CAPS LOCK function key. ASCII: device-ctrl-four. */ - public static final short VK_CAPS_LOCK = (short) 0x14; + short VK_CAPS_LOCK = (short) 0x14; - static final short VK_FREE15 = (short) 0x15; + short VK_FREE15 = (short) 0x15; /** Constant for the PAUSE function key. ASCII: sync-idle. */ - public static final short VK_PAUSE = (short) 0x16; + short VK_PAUSE = (short) 0x16; /** scroll lock key. ASCII: End Of Transmission Block. */ - public static final short VK_SCROLL_LOCK = (short) 0x17; + short VK_SCROLL_LOCK = (short) 0x17; /** Constant for the CANCEL function key. ASCII: Cancel. */ - public static final short VK_CANCEL = (short) 0x18; + short VK_CANCEL = (short) 0x18; - static final short VK_FREE19 = (short) 0x19; + short VK_FREE19 = (short) 0x19; /** Constant for the INSERT function key. ASCII: Substitute. */ - public static final short VK_INSERT = (short) 0x1A; + short VK_INSERT = (short) 0x1A; /** Constant for the ESCAPE function key. ASCII: Escape. */ - public static final short VK_ESCAPE = (short) 0x1B; + short VK_ESCAPE = (short) 0x1B; /** * Constant for the Convert function key, Japanese "henkan". ASCII: File * Separator. */ - public static final short VK_CONVERT = (short) 0x1C; + short VK_CONVERT = (short) 0x1C; /** * Constant for the Don't Convert function key, Japanese "muhenkan". ASCII: * Group Separator. */ - public static final short VK_NONCONVERT = (short) 0x1D; + short VK_NONCONVERT = (short) 0x1D; /** * Constant for the Accept or Commit function key, Japanese "kakutei". * ASCII: Record Separator. */ - public static final short VK_ACCEPT = (short) 0x1E; + short VK_ACCEPT = (short) 0x1E; /** Constant for the Mode Change (?). ASCII: Unit Separator. */ - public static final short VK_MODECHANGE = (short) 0x1F; + short VK_MODECHANGE = (short) 0x1F; // // Unicode: Printable [0x20 - 0x7E] @@ -118,168 +118,168 @@ public interface KeyboardJogampValues { // /** Constant for the SPACE function key. ASCII: SPACE. */ - public static final short VK_SPACE = (short) 0x20; + short VK_SPACE = (short) 0x20; /** Constant for the "!" key. */ - public static final short VK_EXCLAMATION_MARK = (short) 0x21; + short VK_EXCLAMATION_MARK = (short) 0x21; /** Constant for the """ key. */ - public static final short VK_QUOTEDBL = (short) 0x22; + short VK_QUOTEDBL = (short) 0x22; /** Constant for the "#" key. */ - public static final short VK_NUMBER_SIGN = (short) 0x23; + short VK_NUMBER_SIGN = (short) 0x23; /** Constant for the "$" key. */ - public static final short VK_DOLLAR = (short) 0x24; + short VK_DOLLAR = (short) 0x24; /** Constant for the "%" key. */ - public static final short VK_PERCENT = (short) 0x25; + short VK_PERCENT = (short) 0x25; /** Constant for the "&" key. */ - public static final short VK_AMPERSAND = (short) 0x26; + short VK_AMPERSAND = (short) 0x26; /** Constant for the "'" key. */ - public static final short VK_QUOTE = (short) 0x27; + short VK_QUOTE = (short) 0x27; /** Constant for the "(" key. */ - public static final short VK_LEFT_PARENTHESIS = (short) 0x28; + short VK_LEFT_PARENTHESIS = (short) 0x28; /** Constant for the ")" key. */ - public static final short VK_RIGHT_PARENTHESIS = (short) 0x29; + short VK_RIGHT_PARENTHESIS = (short) 0x29; /** Constant for the "*" key */ - public static final short VK_ASTERISK = (short) 0x2A; + short VK_ASTERISK = (short) 0x2A; /** Constant for the "+" key. */ - public static final short VK_PLUS = (short) 0x2B; + short VK_PLUS = (short) 0x2B; /** Constant for the comma key, "," */ - public static final short VK_COMMA = (short) 0x2C; + short VK_COMMA = (short) 0x2C; /** Constant for the minus key, "-" */ - public static final short VK_MINUS = (short) 0x2D; + short VK_MINUS = (short) 0x2D; /** Constant for the period key, "." */ - public static final short VK_PERIOD = (short) 0x2E; + short VK_PERIOD = (short) 0x2E; /** Constant for the forward slash key, "/" */ - public static final short VK_SLASH = (short) 0x2F; + short VK_SLASH = (short) 0x2F; /** VK_0 thru VK_9 are the same as UTF16/ASCII '0' thru '9' [0x30 - 0x39] */ - public static final short VK_0 = (short) 0x30; + short VK_0 = (short) 0x30; /** See {@link #VK_0}. */ - public static final short VK_1 = (short) 0x31; + short VK_1 = (short) 0x31; /** See {@link #VK_0}. */ - public static final short VK_2 = (short) 0x32; + short VK_2 = (short) 0x32; /** See {@link #VK_0}. */ - public static final short VK_3 = (short) 0x33; + short VK_3 = (short) 0x33; /** See {@link #VK_0}. */ - public static final short VK_4 = (short) 0x34; + short VK_4 = (short) 0x34; /** See {@link #VK_0}. */ - public static final short VK_5 = (short) 0x35; + short VK_5 = (short) 0x35; /** See {@link #VK_0}. */ - public static final short VK_6 = (short) 0x36; + short VK_6 = (short) 0x36; /** See {@link #VK_0}. */ - public static final short VK_7 = (short) 0x37; + short VK_7 = (short) 0x37; /** See {@link #VK_0}. */ - public static final short VK_8 = (short) 0x38; + short VK_8 = (short) 0x38; /** See {@link #VK_0}. */ - public static final short VK_9 = (short) 0x39; + short VK_9 = (short) 0x39; /** Constant for the ":" key. */ - public static final short VK_COLON = (short) 0x3A; + short VK_COLON = (short) 0x3A; /** Constant for the semicolon key, ";" */ - public static final short VK_SEMICOLON = (short) 0x3B; + short VK_SEMICOLON = (short) 0x3B; /** Constant for the equals key, "<" */ - public static final short VK_LESS = (short) 0x3C; + short VK_LESS = (short) 0x3C; /** Constant for the equals key, "=" */ - public static final short VK_EQUALS = (short) 0x3D; + short VK_EQUALS = (short) 0x3D; /** Constant for the equals key, ">" */ - public static final short VK_GREATER = (short) 0x3E; + short VK_GREATER = (short) 0x3E; /** Constant for the equals key, "?" */ - public static final short VK_QUESTIONMARK = (short) 0x3F; + short VK_QUESTIONMARK = (short) 0x3F; /** Constant for the equals key, "@" */ - public static final short VK_AT = (short) 0x40; + short VK_AT = (short) 0x40; /** * VK_A thru VK_Z are the same as Capital UTF16/ASCII 'A' thru 'Z' (0x41 - * 0x5A) */ - public static final short VK_A = (short) 0x41; + short VK_A = (short) 0x41; /** See {@link #VK_A}. */ - public static final short VK_B = (short) 0x42; + short VK_B = (short) 0x42; /** See {@link #VK_A}. */ - public static final short VK_C = (short) 0x43; + short VK_C = (short) 0x43; /** See {@link #VK_A}. */ - public static final short VK_D = (short) 0x44; + short VK_D = (short) 0x44; /** See {@link #VK_A}. */ - public static final short VK_E = (short) 0x45; + short VK_E = (short) 0x45; /** See {@link #VK_A}. */ - public static final short VK_F = (short) 0x46; + short VK_F = (short) 0x46; /** See {@link #VK_A}. */ - public static final short VK_G = (short) 0x47; + short VK_G = (short) 0x47; /** See {@link #VK_A}. */ - public static final short VK_H = (short) 0x48; + short VK_H = (short) 0x48; /** See {@link #VK_A}. */ - public static final short VK_I = (short) 0x49; + short VK_I = (short) 0x49; /** See {@link #VK_A}. */ - public static final short VK_J = (short) 0x4A; + short VK_J = (short) 0x4A; /** See {@link #VK_A}. */ - public static final short VK_K = (short) 0x4B; + short VK_K = (short) 0x4B; /** See {@link #VK_A}. */ - public static final short VK_L = (short) 0x4C; + short VK_L = (short) 0x4C; /** See {@link #VK_A}. */ - public static final short VK_M = (short) 0x4D; + short VK_M = (short) 0x4D; /** See {@link #VK_A}. */ - public static final short VK_N = (short) 0x4E; + short VK_N = (short) 0x4E; /** See {@link #VK_A}. */ - public static final short VK_O = (short) 0x4F; + short VK_O = (short) 0x4F; /** See {@link #VK_A}. */ - public static final short VK_P = (short) 0x50; + short VK_P = (short) 0x50; /** See {@link #VK_A}. */ - public static final short VK_Q = (short) 0x51; + short VK_Q = (short) 0x51; /** See {@link #VK_A}. */ - public static final short VK_R = (short) 0x52; + short VK_R = (short) 0x52; /** See {@link #VK_A}. */ - public static final short VK_S = (short) 0x53; + short VK_S = (short) 0x53; /** See {@link #VK_A}. */ - public static final short VK_T = (short) 0x54; + short VK_T = (short) 0x54; /** See {@link #VK_A}. */ - public static final short VK_U = (short) 0x55; + short VK_U = (short) 0x55; /** See {@link #VK_A}. */ - public static final short VK_V = (short) 0x56; + short VK_V = (short) 0x56; /** See {@link #VK_A}. */ - public static final short VK_W = (short) 0x57; + short VK_W = (short) 0x57; /** See {@link #VK_A}. */ - public static final short VK_X = (short) 0x58; + short VK_X = (short) 0x58; /** See {@link #VK_A}. */ - public static final short VK_Y = (short) 0x59; + short VK_Y = (short) 0x59; /** See {@link #VK_A}. */ - public static final short VK_Z = (short) 0x5A; + short VK_Z = (short) 0x5A; /** Constant for the open bracket key, "[" */ - public static final short VK_OPEN_BRACKET = (short) 0x5B; + short VK_OPEN_BRACKET = (short) 0x5B; /** Constant for the back slash key, "\" */ - public static final short VK_BACK_SLASH = (short) 0x5C; + short VK_BACK_SLASH = (short) 0x5C; /** Constant for the close bracket key, "]" */ - public static final short VK_CLOSE_BRACKET = (short) 0x5D; + short VK_CLOSE_BRACKET = (short) 0x5D; /** Constant for the "^" key. */ - public static final short VK_CIRCUMFLEX = (short) 0x5E; + short VK_CIRCUMFLEX = (short) 0x5E; /** Constant for the "_" key */ - public static final short VK_UNDERSCORE = (short) 0x5F; + short VK_UNDERSCORE = (short) 0x5F; /** Constant for the "`" key */ - public static final short VK_BACK_QUOTE = (short) 0x60; + short VK_BACK_QUOTE = (short) 0x60; /** * Small UTF/ASCII 'a' thru 'z' (0x61 - 0x7a) - Not used for keyCode / @@ -298,86 +298,86 @@ public interface KeyboardJogampValues { * See Unicode Collision for details. *

*/ - public static final short VK_F1 = (short) (0x60 + 1); + short VK_F1 = (short) (0x60 + 1); /** Constant for the F2 function key. See {@link #VK_F1}. */ - public static final short VK_F2 = (short) (0x60 + 2); + short VK_F2 = (short) (0x60 + 2); /** Constant for the F3 function key. See {@link #VK_F1}. */ - public static final short VK_F3 = (short) (0x60 + 3); + short VK_F3 = (short) (0x60 + 3); /** Constant for the F4 function key. See {@link #VK_F1}. */ - public static final short VK_F4 = (short) (0x60 + 4); + short VK_F4 = (short) (0x60 + 4); /** Constant for the F5 function key. See {@link #VK_F1}. */ - public static final short VK_F5 = (short) (0x60 + 5); + short VK_F5 = (short) (0x60 + 5); /** Constant for the F6 function key. See {@link #VK_F1}. */ - public static final short VK_F6 = (short) (0x60 + 6); + short VK_F6 = (short) (0x60 + 6); /** Constant for the F7 function key. See {@link #VK_F1}. */ - public static final short VK_F7 = (short) (0x60 + 7); + short VK_F7 = (short) (0x60 + 7); /** Constant for the F8 function key. See {@link #VK_F1}. */ - public static final short VK_F8 = (short) (0x60 + 8); + short VK_F8 = (short) (0x60 + 8); /** Constant for the F9 function key. See {@link #VK_F1}. */ - public static final short VK_F9 = (short) (0x60 + 9); + short VK_F9 = (short) (0x60 + 9); /** Constant for the F11 function key. See {@link #VK_F1}. */ - public static final short VK_F10 = (short) (0x60 + 10); + short VK_F10 = (short) (0x60 + 10); /** Constant for the F11 function key. See {@link #VK_F1}. */ - public static final short VK_F11 = (short) (0x60 + 11); + short VK_F11 = (short) (0x60 + 11); /** Constant for the F12 function key. See {@link #VK_F1}. */ - public static final short VK_F12 = (short) (0x60 + 12); + short VK_F12 = (short) (0x60 + 12); /** Constant for the F13 function key. See {@link #VK_F1}. */ - public static final short VK_F13 = (short) (0x60 + 13); + short VK_F13 = (short) (0x60 + 13); /** Constant for the F14 function key. See {@link #VK_F1}. */ - public static final short VK_F14 = (short) (0x60 + 14); + short VK_F14 = (short) (0x60 + 14); /** Constant for the F15 function key. See {@link #VK_F1}. */ - public static final short VK_F15 = (short) (0x60 + 15); + short VK_F15 = (short) (0x60 + 15); /** Constant for the F16 function key. See {@link #VK_F1}. */ - public static final short VK_F16 = (short) (0x60 + 16); + short VK_F16 = (short) (0x60 + 16); /** Constant for the F17 function key. See {@link #VK_F1}. */ - public static final short VK_F17 = (short) (0x60 + 17); + short VK_F17 = (short) (0x60 + 17); /** Constant for the F18 function key. See {@link #VK_F1}. */ - public static final short VK_F18 = (short) (0x60 + 18); + short VK_F18 = (short) (0x60 + 18); /** Constant for the F19 function key. See {@link #VK_F1}. */ - public static final short VK_F19 = (short) (0x60 + 19); + short VK_F19 = (short) (0x60 + 19); /** Constant for the F20 function key. See {@link #VK_F1}. */ - public static final short VK_F20 = (short) (0x60 + 20); + short VK_F20 = (short) (0x60 + 20); /** Constant for the F21 function key. See {@link #VK_F1}. */ - public static final short VK_F21 = (short) (0x60 + 21); + short VK_F21 = (short) (0x60 + 21); /** Constant for the F22 function key. See {@link #VK_F1}. */ - public static final short VK_F22 = (short) (0x60 + 22); + short VK_F22 = (short) (0x60 + 22); /** Constant for the F23 function key. See {@link #VK_F1}. */ - public static final short VK_F23 = (short) (0x60 + 23); + short VK_F23 = (short) (0x60 + 23); /** Constant for the F24 function key. See {@link #VK_F1}. */ - public static final short VK_F24 = (short) (0x60 + 24); + short VK_F24 = (short) (0x60 + 24); /** Constant for the "{" key */ - public static final short VK_LEFT_BRACE = (short) 0x7B; + short VK_LEFT_BRACE = (short) 0x7B; /** Constant for the "|" key */ - public static final short VK_PIPE = (short) 0x7C; + short VK_PIPE = (short) 0x7C; /** Constant for the "}" key */ - public static final short VK_RIGHT_BRACE = (short) 0x7D; + short VK_RIGHT_BRACE = (short) 0x7D; /** Constant for the "~" key, matching ASCII */ - public static final short VK_TILDE = (short) 0x7E; + short VK_TILDE = (short) 0x7E; // // Unicode: Non printable controls: [0x7F - 0x9F] @@ -388,125 +388,125 @@ public interface KeyboardJogampValues { /** * Numeric keypad decimal separator key. Non printable UTF control. */ - public static final short VK_SEPARATOR = (short) 0x7F; + short VK_SEPARATOR = (short) 0x7F; /** * Numeric keypad VK_NUMPAD0 thru VK_NUMPAD9 are mapped to UTF control (0x80 * - 0x89). Non printable UTF control. */ - public static final short VK_NUMPAD0 = (short) 0x80; + short VK_NUMPAD0 = (short) 0x80; /** See {@link #VK_NUMPAD0}. */ - public static final short VK_NUMPAD1 = (short) 0x81; + short VK_NUMPAD1 = (short) 0x81; /** See {@link #VK_NUMPAD0}. */ - public static final short VK_NUMPAD2 = (short) 0x82; + short VK_NUMPAD2 = (short) 0x82; /** See {@link #VK_NUMPAD0}. */ - public static final short VK_NUMPAD3 = (short) 0x83; + short VK_NUMPAD3 = (short) 0x83; /** See {@link #VK_NUMPAD0}. */ - public static final short VK_NUMPAD4 = (short) 0x84; + short VK_NUMPAD4 = (short) 0x84; /** See {@link #VK_NUMPAD0}. */ - public static final short VK_NUMPAD5 = (short) 0x85; + short VK_NUMPAD5 = (short) 0x85; /** See {@link #VK_NUMPAD0}. */ - public static final short VK_NUMPAD6 = (short) 0x86; + short VK_NUMPAD6 = (short) 0x86; /** See {@link #VK_NUMPAD0}. */ - public static final short VK_NUMPAD7 = (short) 0x87; + short VK_NUMPAD7 = (short) 0x87; /** See {@link #VK_NUMPAD0}. */ - public static final short VK_NUMPAD8 = (short) 0x88; + short VK_NUMPAD8 = (short) 0x88; /** See {@link #VK_NUMPAD0}. */ - public static final short VK_NUMPAD9 = (short) 0x89; + short VK_NUMPAD9 = (short) 0x89; /** * Numeric keypad decimal separator key. Non printable UTF control. */ - public static final short VK_DECIMAL = (short) 0x8A; + short VK_DECIMAL = (short) 0x8A; /** Numeric keypad add key. Non printable UTF control. */ - public static final short VK_ADD = (short) 0x8B; + short VK_ADD = (short) 0x8B; /** Numeric keypad subtract key. Non printable UTF control. */ - public static final short VK_SUBTRACT = (short) 0x8C; + short VK_SUBTRACT = (short) 0x8C; /** Numeric keypad multiply key. Non printable UTF control. */ - public static final short VK_MULTIPLY = (short) 0x8D; + short VK_MULTIPLY = (short) 0x8D; /** Numeric keypad divide key. Non printable UTF control. */ - public static final short VK_DIVIDE = (short) 0x8E; + short VK_DIVIDE = (short) 0x8E; /** Constant for the DEL key, matching ASCII. Non printable UTF control. */ - public static final short VK_DELETE = (short) 0x93; + short VK_DELETE = (short) 0x93; /** Numeric keypad num lock key. Non printable UTF control. */ - public static final short VK_NUM_LOCK = (short) 0x94; + short VK_NUM_LOCK = (short) 0x94; /** * Constant for the cursor- or numerical-pad left arrow key. Non * printable UTF control. */ - public static final short VK_LEFT = (short) 0x95; + short VK_LEFT = (short) 0x95; /** * Constant for the cursor- or numerical-pad up arrow key. Non * printable UTF control. */ - public static final short VK_UP = (short) 0x96; + short VK_UP = (short) 0x96; /** * Constant for the cursor- or numerical-pad right arrow key. Non * printable UTF control. */ - public static final short VK_RIGHT = (short) 0x97; + short VK_RIGHT = (short) 0x97; /** * Constant for the cursor- or numerical pad down arrow key. Non * printable UTF control. */ - public static final short VK_DOWN = (short) 0x98; + short VK_DOWN = (short) 0x98; /** Constant for the Context Menu key. Non printable UTF control. */ - public static final short VK_CONTEXT_MENU = (short) 0x99; + short VK_CONTEXT_MENU = (short) 0x99; /** * Constant for the MS "Windows" function key. * It is used for both the left and right version of the key. */ - public static final short VK_WINDOWS = (short) 0x9A; + short VK_WINDOWS = (short) 0x9A; /** Constant for the Meta function key. */ - public static final short VK_META = (short) 0x9B; + short VK_META = (short) 0x9B; /** Constant for the Help function key. */ - public static final short VK_HELP = (short) 0x9C; + short VK_HELP = (short) 0x9C; /** Constant for the Compose function key. */ - public static final short VK_COMPOSE = (short) 0x9D; + short VK_COMPOSE = (short) 0x9D; /** Constant for the Begin function key. */ - public static final short VK_BEGIN = (short) 0x9E; + short VK_BEGIN = (short) 0x9E; /** Constant for the Stop function key. */ - public static final short VK_STOP = (short) 0x9F; + short VK_STOP = (short) 0x9F; // // Unicode: Printable [0x00A0 - 0xDFFF] // /** Constant for the inverted exclamation mark key. */ - public static final short VK_INVERTED_EXCLAMATION_MARK = (short) 0xA1; + short VK_INVERTED_EXCLAMATION_MARK = (short) 0xA1; /** Constant for the Euro currency sign key. */ - public static final short VK_EURO_SIGN = (short) 0x20AC; + short VK_EURO_SIGN = (short) 0x20AC; // // Unicode: Private 0xE000 - 0xF8FF (Marked Non-Printable) // /* for Sun keyboards */ - public static final short VK_CUT = (short) 0xF879; - public static final short VK_COPY = (short) 0xF87A; - public static final short VK_PASTE = (short) 0xF87B; - public static final short VK_UNDO = (short) 0xF87C; - public static final short VK_AGAIN = (short) 0xF87D; - public static final short VK_FIND = (short) 0xF87E; - public static final short VK_PROPS = (short) 0xF87F; + short VK_CUT = (short) 0xF879; + short VK_COPY = (short) 0xF87A; + short VK_PASTE = (short) 0xF87B; + short VK_UNDO = (short) 0xF87C; + short VK_AGAIN = (short) 0xF87D; + short VK_FIND = (short) 0xF87E; + short VK_PROPS = (short) 0xF87F; /* for input method support on Asian Keyboards */ @@ -514,61 +514,61 @@ public interface KeyboardJogampValues { * Constant for the input method on/off key. */ /* Japanese PC 106 keyboard: kanji. Japanese Solaris keyboard: nihongo */ - public static final short VK_INPUT_METHOD_ON_OFF = (short) 0xF890; + short VK_INPUT_METHOD_ON_OFF = (short) 0xF890; /** * Constant for the Code Input function key. */ /* Japanese PC 106 keyboard - VK_ALPHANUMERIC + ALT: kanji bangou */ - public static final short VK_CODE_INPUT = (short) 0xF891; + short VK_CODE_INPUT = (short) 0xF891; /** * Constant for the Roman Characters function key. */ /* Japanese PC 106 keyboard: roumaji */ - public static final short VK_ROMAN_CHARACTERS = (short) 0xF892; + short VK_ROMAN_CHARACTERS = (short) 0xF892; /** * Constant for the All Candidates function key. */ /* Japanese PC 106 keyboard - VK_CONVERT + ALT: zenkouho */ - public static final short VK_ALL_CANDIDATES = (short) 0xF893; + short VK_ALL_CANDIDATES = (short) 0xF893; /** * Constant for the Previous Candidate function key. */ /* Japanese PC 106 keyboard - VK_CONVERT + SHIFT: maekouho */ - public static final short VK_PREVIOUS_CANDIDATE = (short) 0xF894; + short VK_PREVIOUS_CANDIDATE = (short) 0xF894; /** * Constant for the Alphanumeric function key. */ /* Japanese PC 106 keyboard: eisuu */ - public static final short VK_ALPHANUMERIC = (short) 0xF895; + short VK_ALPHANUMERIC = (short) 0xF895; /** * Constant for the Katakana function key. */ /* Japanese PC 106 keyboard: katakana */ - public static final short VK_KATAKANA = (short) 0xF896; + short VK_KATAKANA = (short) 0xF896; /** * Constant for the Hiragana function key. */ /* Japanese PC 106 keyboard: hiragana */ - public static final short VK_HIRAGANA = (short) 0xF897; + short VK_HIRAGANA = (short) 0xF897; /** * Constant for the Full-Width Characters function key. */ /* Japanese PC 106 keyboard: zenkaku */ - public static final short VK_FULL_WIDTH = (short) 0xF898; + short VK_FULL_WIDTH = (short) 0xF898; /** * Constant for the Half-Width Characters function key. */ /* Japanese PC 106 keyboard: hankaku */ - public static final short VK_HALF_WIDTH = (short) 0xF89A; + short VK_HALF_WIDTH = (short) 0xF89A; /** * Constant for the Japanese-Katakana function key. @@ -576,7 +576,7 @@ public interface KeyboardJogampValues { * input mode. */ /* Japanese Macintosh keyboard - VK_JAPANESE_HIRAGANA + SHIFT */ - public static final short VK_JAPANESE_KATAKANA = (short) 0xF89B; + short VK_JAPANESE_KATAKANA = (short) 0xF89B; /** * Constant for the Japanese-Hiragana function key. @@ -584,7 +584,7 @@ public interface KeyboardJogampValues { * input mode. */ /* Japanese Macintosh keyboard */ - public static final short VK_JAPANESE_HIRAGANA = (short) 0xF89C; + short VK_JAPANESE_HIRAGANA = (short) 0xF89C; /** * Constant for the Japanese-Roman function key. @@ -592,19 +592,19 @@ public interface KeyboardJogampValues { * input mode. */ /* Japanese Macintosh keyboard */ - public static final short VK_JAPANESE_ROMAN = (short) 0xF89D; + short VK_JAPANESE_ROMAN = (short) 0xF89D; /** * Constant for the locking Kana function key. * This key locks the keyboard into a Kana layout. */ /* Japanese PC 106 keyboard with special Windows driver - eisuu + Control; Japanese Solaris keyboard: kana */ - public static final short VK_KANA_LOCK = (short) 0xF89F; + short VK_KANA_LOCK = (short) 0xF89F; /** * Constant for Keyboard became invisible, e.g. Android's soft keyboard Back * button hit while keyboard is visible. */ - public static final short VK_KEYBOARD_INVISIBLE = (short) 0xF8FF; + short VK_KEYBOARD_INVISIBLE = (short) 0xF8FF; } diff --git a/core/src/main/java/it/cavallium/warppi/device/PIHardwareDisplay.java b/core/src/main/java/it/cavallium/warppi/device/PIHardwareDisplay.java index b29326b9..ab052483 100644 --- a/core/src/main/java/it/cavallium/warppi/device/PIHardwareDisplay.java +++ b/core/src/main/java/it/cavallium/warppi/device/PIHardwareDisplay.java @@ -12,13 +12,12 @@ public class PIHardwareDisplay implements HardwareDisplay { public void shutdown() {} @Override - public void setBrightness(double value) { - if (Engine.getPlatform().getSettings().isDebugEnabled() == false) { + public void setBrightness(final double value) { + if (Engine.getPlatform().getSettings().isDebugEnabled() == false) Engine.getPlatform().getGpio().pwmWrite(12, (int) Math.ceil(value * 1024f)); // SoftPwm.softPwmWrite(12, (int)(Math.ceil(brightness*10))); - } else { + else Engine.getPlatform().getConsoleUtils().out().println(1, "Brightness: " + value); - } } } diff --git a/core/src/main/java/it/cavallium/warppi/device/PIHardwareTouchDevice.java b/core/src/main/java/it/cavallium/warppi/device/PIHardwareTouchDevice.java index 0acde74a..f91aad95 100644 --- a/core/src/main/java/it/cavallium/warppi/device/PIHardwareTouchDevice.java +++ b/core/src/main/java/it/cavallium/warppi/device/PIHardwareTouchDevice.java @@ -12,69 +12,65 @@ public class PIHardwareTouchDevice implements HardwareTouchDevice { private final boolean invertXY, invertX, invertY; - public PIHardwareTouchDevice(boolean invertXY, boolean invertX, boolean invertY) { + public PIHardwareTouchDevice(final boolean invertXY, final boolean invertX, final boolean invertY) { this.invertXY = invertXY; this.invertX = invertX; this.invertY = invertY; } @Override - public boolean onTouchStart(TouchStartEvent e) { + public boolean onTouchStart(final TouchStartEvent e) { final Screen scr = Engine.INSTANCE.getHardwareDevice().getDisplayManager().getScreen(); boolean refresh = false; - if (scr != null && scr.initialized && scr.onTouchStart(e)) { + if (scr != null && scr.initialized && scr.onTouchStart(e)) refresh = true; - } else { + else { //Default behavior } - if (refresh) { + if (refresh) Engine.INSTANCE.getHardwareDevice().getDisplayManager().forceRefresh = true; - } return true; } @Override - public boolean onTouchEnd(TouchEndEvent e) { + public boolean onTouchEnd(final TouchEndEvent e) { final Screen scr = Engine.INSTANCE.getHardwareDevice().getDisplayManager().getScreen(); boolean refresh = false; - if (scr != null && scr.initialized && scr.onTouchEnd(e)) { + if (scr != null && scr.initialized && scr.onTouchEnd(e)) refresh = true; - } else { + else { //Default behavior } - if (refresh) { + if (refresh) Engine.INSTANCE.getHardwareDevice().getDisplayManager().forceRefresh = true; - } return true; } @Override - public boolean onTouchCancel(TouchCancelEvent e) { + public boolean onTouchCancel(final TouchCancelEvent e) { final Screen scr = Engine.INSTANCE.getHardwareDevice().getDisplayManager().getScreen(); boolean refresh = false; - if (scr != null && scr.initialized && scr.onTouchCancel(e)) { + if (scr != null && scr.initialized && scr.onTouchCancel(e)) refresh = true; - } else { + else { //Default behavior } - if (refresh) { + if (refresh) Engine.INSTANCE.getHardwareDevice().getDisplayManager().forceRefresh = true; - } return true; } @Override - public boolean onTouchMove(TouchMoveEvent e) { + public boolean onTouchMove(final TouchMoveEvent e) { final Screen scr = Engine.INSTANCE.getHardwareDevice().getDisplayManager().getScreen(); boolean refresh = false; - if (scr != null && scr.initialized && scr.onTouchMove(e)) { + if (scr != null && scr.initialized && scr.onTouchMove(e)) refresh = true; - } else { + else { //Default behavior } - if (refresh) { + if (refresh) Engine.INSTANCE.getHardwareDevice().getDisplayManager().forceRefresh = true; - } return true; } @@ -94,20 +90,18 @@ public class PIHardwareTouchDevice implements HardwareTouchDevice { } @Override - public TouchPoint makePoint(long id, float x, float y, int screenWidth, int screenHeight, float radiusX, - float radiusY, float force, float rotationAngle) { + public TouchPoint makePoint(final long id, float x, float y, final int screenWidth, final int screenHeight, + final float radiusX, final float radiusY, final float force, final float rotationAngle) { if (getInvertedXY()) { - double oldX = x; - double oldY = y; - x = (float) (oldY * ((double) screenWidth) / ((double) screenHeight)); - y = (float) (oldX * ((double) screenHeight) / ((double) screenWidth)); + final double oldX = x; + final double oldY = y; + x = (float) (oldY * screenWidth / screenHeight); + y = (float) (oldX * screenHeight / screenWidth); } - if (getInvertedX()) { + if (getInvertedX()) x = screenWidth - x; - } - if (getInvertedY()) { + if (getInvertedY()) y = screenHeight - y; - } return new TouchPoint(id, x, y, radiusX, radiusY, force, rotationAngle); } } diff --git a/core/src/main/java/it/cavallium/warppi/device/chip/ParallelToSerial.java b/core/src/main/java/it/cavallium/warppi/device/chip/ParallelToSerial.java index 51f815c9..dfc74e6d 100644 --- a/core/src/main/java/it/cavallium/warppi/device/chip/ParallelToSerial.java +++ b/core/src/main/java/it/cavallium/warppi/device/chip/ParallelToSerial.java @@ -9,7 +9,7 @@ public class ParallelToSerial { private final int QH; private final int CLK; - public ParallelToSerial(int SH_LD_pin, int CLK_INH_pin, int QH_pin, int CLK_pin) { + public ParallelToSerial(final int SH_LD_pin, final int CLK_INH_pin, final int QH_pin, final int CLK_pin) { SH_LD = SH_LD_pin; CLK_INH = CLK_INH_pin; QH = QH_pin; diff --git a/core/src/main/java/it/cavallium/warppi/device/chip/SerialToParallel.java b/core/src/main/java/it/cavallium/warppi/device/chip/SerialToParallel.java index 56e53027..f5563280 100644 --- a/core/src/main/java/it/cavallium/warppi/device/chip/SerialToParallel.java +++ b/core/src/main/java/it/cavallium/warppi/device/chip/SerialToParallel.java @@ -7,16 +7,16 @@ public class SerialToParallel { private final int SCK; //Shift register clock pin private final int SER; //Serial data input - public SerialToParallel(int RCK_pin, int SCK_pin, int SER_pin) { + public SerialToParallel(final int RCK_pin, final int SCK_pin, final int SER_pin) { RCK = RCK_pin; SCK = SCK_pin; SER = SER_pin; } - public void write(boolean[] data) { - if (data.length != 8) { + public void write(final boolean[] data) { + if (data.length != 8) return; - } else { + else { Engine.getPlatform().getGpio().digitalWrite(RCK, Engine.getPlatform().getGpio().valueLow()); for (int i = 7; i >= 0; i--) { diff --git a/core/src/main/java/it/cavallium/warppi/device/graphicengine/RAWFont.java b/core/src/main/java/it/cavallium/warppi/device/graphicengine/RAWFont.java index 0b69f52f..fd7ca8de 100644 --- a/core/src/main/java/it/cavallium/warppi/device/graphicengine/RAWFont.java +++ b/core/src/main/java/it/cavallium/warppi/device/graphicengine/RAWFont.java @@ -31,7 +31,7 @@ public class RAWFont { public int charIntCount; public static final int intBits = 31; - public void create(String name) { + public void create(final String name) { try { loadFont("/font_" + name + ".rft"); } catch (final IOException e) { @@ -45,7 +45,7 @@ public class RAWFont { int currentInt = 0; int currentBit = 0; for (int i = 0; i < charS; i++) { - if (currentInt * intBits + currentBit >= (currentInt + 1) * intBits) { + if (currentInt * RAWFont.intBits + currentBit >= (currentInt + 1) * RAWFont.intBits) { currentInt += 1; currentBit = 0; } @@ -56,11 +56,11 @@ public class RAWFont { int currentInt = 0; int currentBit = 0; for (int i = 0; i < charS; i++) { - if (currentBit >= intBits) { + if (currentBit >= RAWFont.intBits) { currentInt += 1; currentBit = 0; } - chars32[charIndex * charIntCount + currentInt] = (chars32[charIndex * charIntCount + currentInt]) | ((currentChar[i] ? 1 : 0) << currentBit); + chars32[charIndex * charIntCount + currentInt] = chars32[charIndex * charIntCount + currentInt] | (currentChar[i] ? 1 : 0) << currentBit; currentBit++; } } @@ -69,12 +69,11 @@ public class RAWFont { Object obj = new Object(); final WeakReference ref = new WeakReference<>(obj); obj = null; - while (ref.get() != null) { + while (ref.get() != null) System.gc(); - } } - private void loadFont(String string) throws IOException { + private void loadFont(final String string) throws IOException { final URL res = ClassUtils.classLoader.getClass().getResource(string); final int[] file = Utils.realBytes(Utils.convertStreamToByteArray(res.openStream(), res.getFile().length())); final int filelength = file.length; @@ -83,32 +82,28 @@ public class RAWFont { charW = file[0x4] << 8 | file[0x5]; charH = file[0x6] << 8 | file[0x7]; charS = charW * charH; - charIntCount = (int) Math.ceil(((double) charS) / ((double) intBits)); + charIntCount = (int) Math.ceil((double) charS / (double) RAWFont.intBits); minBound = file[0x9] << 24 | file[0xA] << 16 | file[0xB] << 8 | file[0xC]; maxBound = file[0xE] << 24 | file[0xF] << 16 | file[0x10] << 8 | file[0x11]; - if (maxBound <= minBound) { + if (maxBound <= minBound) maxBound = 10000; //TODO remove it: temp fix - } rawchars = new boolean[maxBound - minBound][]; int index = 0x12; - while (index < filelength) { + while (index < filelength) try { final int charIndex = file[index] << 8 | file[index + 1]; final boolean[] rawchar = new boolean[charS]; int charbytescount = 0; - while (charbytescount * 8 < charS) { + while (charbytescount * 8 < charS) charbytescount += 1; - } int currentBit = 0; - for (int i = 0; i <= charbytescount; i++) { + for (int i = 0; i <= charbytescount; i++) for (int bit = 0; bit < 8; bit++) { - if (currentBit >= charS) { + if (currentBit >= charS) break; - } - rawchar[currentBit] = (((file[index + 2 + i] >> (8 - 1 - bit)) & 0x1) == 1) ? true : false; + rawchar[currentBit] = (file[index + 2 + i] >> 8 - 1 - bit & 0x1) == 1 ? true : false; currentBit++; } - } rawchars[charIndex - minBound] = rawchar; index += 2 + charbytescount; } catch (final Exception ex) { @@ -116,27 +111,23 @@ public class RAWFont { System.out.println(string); Engine.getPlatform().exit(-1); } - } - } else { + } else throw new IOException(); - } - } else { + } else throw new IOException(); - } } - public int[] getCharIndexes(String txt) { + public int[] getCharIndexes(final String txt) { final int l = txt.length(); final int[] indexes = new int[l]; final char[] chars = txt.toCharArray(); - for (int i = 0; i < l; i++) { + for (int i = 0; i < l; i++) indexes[i] = (chars[i] & 0xFFFF) - minBound; - } return indexes; } @SuppressWarnings("unused") - private void saveArray(int[] screen, String coutputpng) { + private void saveArray(final int[] screen, final String coutputpng) { final BufferedImage bi = new BufferedImage(300, 200, BufferedImage.TYPE_INT_RGB); final int[] a = ((DataBufferInt) bi.getRaster().getDataBuffer()).getData(); System.arraycopy(screen, 0, a, 0, screen.length); @@ -147,7 +138,8 @@ public class RAWFont { } } - public void drawText(int[] screen, int[] screenSize, int x, int y, int[] text, int color) { + public void drawText(final int[] screen, final int[] screenSize, final int x, final int y, final int[] text, + final int color) { final int screenLength = screen.length; int screenPos = 0; @@ -158,23 +150,21 @@ public class RAWFont { int j; final int l = text.length; for (int i = 0; i < l; i++) { - cpos = (i * (charW + 1)); + cpos = i * (charW + 1); final int charIndex = text[i]; - for (int dy = 0; dy < charH; dy++) { + for (int dy = 0; dy < charH; dy++) for (int dx = 0; dx < charW; dx++) { j = x + cpos + dx; if (j > 0 & j < screenSize[0]) { final int bit = dx + dy * charW; - currentInt = (int) (Math.floor(bit) / (intBits)); - currentIntBitPosition = bit - (currentInt * intBits); - bitData = (chars32[charIndex * charIntCount + currentInt] >> currentIntBitPosition) & 1; + currentInt = (int) (Math.floor(bit) / RAWFont.intBits); + currentIntBitPosition = bit - currentInt * RAWFont.intBits; + bitData = chars32[charIndex * charIntCount + currentInt] >> currentIntBitPosition & 1; screenPos = x + cpos + dx + (y + dy) * screenSize[0]; - if (bitData == 1 & screenLength > screenPos) { + if (bitData == 1 & screenLength > screenPos) screen[screenPos] = color; - } } } - } } } } diff --git a/core/src/main/java/it/cavallium/warppi/event/KeyEvent.java b/core/src/main/java/it/cavallium/warppi/event/KeyEvent.java index f5dd53fb..df12c188 100644 --- a/core/src/main/java/it/cavallium/warppi/event/KeyEvent.java +++ b/core/src/main/java/it/cavallium/warppi/event/KeyEvent.java @@ -1,5 +1,5 @@ package it.cavallium.warppi.event; public interface KeyEvent extends Event { - public Key getKey(); + Key getKey(); } diff --git a/core/src/main/java/it/cavallium/warppi/event/KeyPressedEvent.java b/core/src/main/java/it/cavallium/warppi/event/KeyPressedEvent.java index 8c43ab81..2d262704 100644 --- a/core/src/main/java/it/cavallium/warppi/event/KeyPressedEvent.java +++ b/core/src/main/java/it/cavallium/warppi/event/KeyPressedEvent.java @@ -2,9 +2,9 @@ package it.cavallium.warppi.event; public class KeyPressedEvent implements KeyEvent { - private Key k; + private final Key k; - public KeyPressedEvent(Key k) { + public KeyPressedEvent(final Key k) { this.k = k; } diff --git a/core/src/main/java/it/cavallium/warppi/event/KeyReleasedEvent.java b/core/src/main/java/it/cavallium/warppi/event/KeyReleasedEvent.java index b1e0daf1..da0c77d5 100644 --- a/core/src/main/java/it/cavallium/warppi/event/KeyReleasedEvent.java +++ b/core/src/main/java/it/cavallium/warppi/event/KeyReleasedEvent.java @@ -2,9 +2,9 @@ package it.cavallium.warppi.event; public class KeyReleasedEvent implements KeyEvent { - private Key k; + private final Key k; - public KeyReleasedEvent(Key k) { + public KeyReleasedEvent(final Key k) { this.k = k; } diff --git a/core/src/main/java/it/cavallium/warppi/event/KeyboardEventListener.java b/core/src/main/java/it/cavallium/warppi/event/KeyboardEventListener.java index 6101459b..027c1b08 100644 --- a/core/src/main/java/it/cavallium/warppi/event/KeyboardEventListener.java +++ b/core/src/main/java/it/cavallium/warppi/event/KeyboardEventListener.java @@ -1,11 +1,11 @@ package it.cavallium.warppi.event; public interface KeyboardEventListener { - public default boolean onKeyPressed(KeyPressedEvent k) { + default boolean onKeyPressed(final KeyPressedEvent k) { return false; } - public default boolean onKeyReleased(KeyReleasedEvent k) { + default boolean onKeyReleased(final KeyReleasedEvent k) { return false; } } diff --git a/core/src/main/java/it/cavallium/warppi/event/TouchCancelEvent.java b/core/src/main/java/it/cavallium/warppi/event/TouchCancelEvent.java index 3618ac3e..7d19b364 100644 --- a/core/src/main/java/it/cavallium/warppi/event/TouchCancelEvent.java +++ b/core/src/main/java/it/cavallium/warppi/event/TouchCancelEvent.java @@ -7,7 +7,7 @@ public class TouchCancelEvent implements TouchEvent { private final List changedTouches; private final List touches; - public TouchCancelEvent(List changedTouches, List touches) { + public TouchCancelEvent(final List changedTouches, final List touches) { super(); this.changedTouches = changedTouches; this.touches = touches; @@ -27,20 +27,20 @@ public class TouchCancelEvent implements TouchEvent { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((changedTouches == null) ? 0 : changedTouches.hashCode()); - result = prime * result + ((touches == null) ? 0 : touches.hashCode()); + result = prime * result + (changedTouches == null ? 0 : changedTouches.hashCode()); + result = prime * result + (touches == null ? 0 : touches.hashCode()); return result; } @Override - public boolean equals(Object obj) { + public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; - TouchCancelEvent other = (TouchCancelEvent) obj; + final TouchCancelEvent other = (TouchCancelEvent) obj; if (changedTouches == null) { if (other.changedTouches != null) return false; diff --git a/core/src/main/java/it/cavallium/warppi/event/TouchEndEvent.java b/core/src/main/java/it/cavallium/warppi/event/TouchEndEvent.java index 27f98186..baa8a31c 100644 --- a/core/src/main/java/it/cavallium/warppi/event/TouchEndEvent.java +++ b/core/src/main/java/it/cavallium/warppi/event/TouchEndEvent.java @@ -7,7 +7,7 @@ public class TouchEndEvent implements TouchEvent { private final List changedTouches; private final List touches; - public TouchEndEvent(List changedTouches, List touches) { + public TouchEndEvent(final List changedTouches, final List touches) { super(); this.changedTouches = changedTouches; this.touches = touches; @@ -27,20 +27,20 @@ public class TouchEndEvent implements TouchEvent { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((changedTouches == null) ? 0 : changedTouches.hashCode()); - result = prime * result + ((touches == null) ? 0 : touches.hashCode()); + result = prime * result + (changedTouches == null ? 0 : changedTouches.hashCode()); + result = prime * result + (touches == null ? 0 : touches.hashCode()); return result; } @Override - public boolean equals(Object obj) { + public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; - TouchEndEvent other = (TouchEndEvent) obj; + final TouchEndEvent other = (TouchEndEvent) obj; if (changedTouches == null) { if (other.changedTouches != null) return false; diff --git a/core/src/main/java/it/cavallium/warppi/event/TouchEvent.java b/core/src/main/java/it/cavallium/warppi/event/TouchEvent.java index 66aa6265..565fbed0 100644 --- a/core/src/main/java/it/cavallium/warppi/event/TouchEvent.java +++ b/core/src/main/java/it/cavallium/warppi/event/TouchEvent.java @@ -3,7 +3,7 @@ package it.cavallium.warppi.event; import java.util.List; public interface TouchEvent extends Event { - public List getChangedTouches(); + List getChangedTouches(); - public List getTouches(); + List getTouches(); } diff --git a/core/src/main/java/it/cavallium/warppi/event/TouchEventListener.java b/core/src/main/java/it/cavallium/warppi/event/TouchEventListener.java index 596fa62a..9dda969b 100644 --- a/core/src/main/java/it/cavallium/warppi/event/TouchEventListener.java +++ b/core/src/main/java/it/cavallium/warppi/event/TouchEventListener.java @@ -1,19 +1,19 @@ package it.cavallium.warppi.event; public interface TouchEventListener { - public default boolean onTouchStart(TouchStartEvent k) { + default boolean onTouchStart(final TouchStartEvent k) { return false; } - public default boolean onTouchEnd(TouchEndEvent k) { + default boolean onTouchEnd(final TouchEndEvent k) { return false; } - public default boolean onTouchCancel(TouchCancelEvent k) { + default boolean onTouchCancel(final TouchCancelEvent k) { return false; } - public default boolean onTouchMove(TouchMoveEvent k) { + default boolean onTouchMove(final TouchMoveEvent k) { return false; } } diff --git a/core/src/main/java/it/cavallium/warppi/event/TouchMoveEvent.java b/core/src/main/java/it/cavallium/warppi/event/TouchMoveEvent.java index 424226b3..cbba6118 100644 --- a/core/src/main/java/it/cavallium/warppi/event/TouchMoveEvent.java +++ b/core/src/main/java/it/cavallium/warppi/event/TouchMoveEvent.java @@ -7,7 +7,7 @@ public class TouchMoveEvent implements TouchEvent { private final List changedTouches; private final List touches; - public TouchMoveEvent(List changedTouches, List touches) { + public TouchMoveEvent(final List changedTouches, final List touches) { super(); this.changedTouches = changedTouches; this.touches = touches; @@ -27,20 +27,20 @@ public class TouchMoveEvent implements TouchEvent { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((changedTouches == null) ? 0 : changedTouches.hashCode()); - result = prime * result + ((touches == null) ? 0 : touches.hashCode()); + result = prime * result + (changedTouches == null ? 0 : changedTouches.hashCode()); + result = prime * result + (touches == null ? 0 : touches.hashCode()); return result; } @Override - public boolean equals(Object obj) { + public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; - TouchMoveEvent other = (TouchMoveEvent) obj; + final TouchMoveEvent other = (TouchMoveEvent) obj; if (changedTouches == null) { if (other.changedTouches != null) return false; diff --git a/core/src/main/java/it/cavallium/warppi/event/TouchPoint.java b/core/src/main/java/it/cavallium/warppi/event/TouchPoint.java index dc46e1cf..9e05fc56 100644 --- a/core/src/main/java/it/cavallium/warppi/event/TouchPoint.java +++ b/core/src/main/java/it/cavallium/warppi/event/TouchPoint.java @@ -9,7 +9,7 @@ public class TouchPoint { private final float y; private final long id; - public TouchPoint(long id, float x, float y, float radiusX, float radiusY, float force, float rotationAngle) { + public TouchPoint(final long id, final float x, final float y, final float radiusX, final float radiusY, final float force, final float rotationAngle) { super(); this.id = id; this.radiusX = radiusX; @@ -53,7 +53,7 @@ public class TouchPoint { final int prime = 31; int result = 1; result = prime * result + Float.floatToIntBits(force); - result = prime * result + (int) (id ^ (id >>> 32)); + result = prime * result + (int) (id ^ id >>> 32); result = prime * result + Float.floatToIntBits(radiusX); result = prime * result + Float.floatToIntBits(radiusY); result = prime * result + Float.floatToIntBits(rotationAngle); @@ -63,14 +63,14 @@ public class TouchPoint { } @Override - public boolean equals(Object obj) { + public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; - TouchPoint other = (TouchPoint) obj; + final TouchPoint other = (TouchPoint) obj; if (Float.floatToIntBits(force) != Float.floatToIntBits(other.force)) return false; if (id != other.id) diff --git a/core/src/main/java/it/cavallium/warppi/event/TouchStartEvent.java b/core/src/main/java/it/cavallium/warppi/event/TouchStartEvent.java index 97c032fc..feb621d6 100644 --- a/core/src/main/java/it/cavallium/warppi/event/TouchStartEvent.java +++ b/core/src/main/java/it/cavallium/warppi/event/TouchStartEvent.java @@ -7,7 +7,7 @@ public class TouchStartEvent implements TouchEvent { private final List changedTouches; private final List touches; - public TouchStartEvent(List changedTouches, List touches) { + public TouchStartEvent(final List changedTouches, final List touches) { super(); this.changedTouches = changedTouches; this.touches = touches; @@ -27,20 +27,20 @@ public class TouchStartEvent implements TouchEvent { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((changedTouches == null) ? 0 : changedTouches.hashCode()); - result = prime * result + ((touches == null) ? 0 : touches.hashCode()); + result = prime * result + (changedTouches == null ? 0 : changedTouches.hashCode()); + result = prime * result + (touches == null ? 0 : touches.hashCode()); return result; } @Override - public boolean equals(Object obj) { + public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; - TouchStartEvent other = (TouchStartEvent) obj; + final TouchStartEvent other = (TouchStartEvent) obj; if (changedTouches == null) { if (other.changedTouches != null) return false; diff --git a/core/src/main/java/it/cavallium/warppi/extra/mario/MarioBlock.java b/core/src/main/java/it/cavallium/warppi/extra/mario/MarioBlock.java index 6f9f7147..68a3f6a5 100644 --- a/core/src/main/java/it/cavallium/warppi/extra/mario/MarioBlock.java +++ b/core/src/main/java/it/cavallium/warppi/extra/mario/MarioBlock.java @@ -5,7 +5,7 @@ public class MarioBlock { private final int y; private final byte id; - public MarioBlock(int x, int y, byte b) { + public MarioBlock(final int x, final int y, final byte b) { this.x = x; this.y = y; id = b; @@ -27,7 +27,7 @@ public class MarioBlock { return y; } - public static boolean isSolid(byte id) { + public static boolean isSolid(final byte id) { return id != 0b0; } } diff --git a/core/src/main/java/it/cavallium/warppi/extra/mario/MarioEnemy.java b/core/src/main/java/it/cavallium/warppi/extra/mario/MarioEnemy.java index 50199268..cc9710a3 100644 --- a/core/src/main/java/it/cavallium/warppi/extra/mario/MarioEnemy.java +++ b/core/src/main/java/it/cavallium/warppi/extra/mario/MarioEnemy.java @@ -2,7 +2,7 @@ package it.cavallium.warppi.extra.mario; public class MarioEnemy extends MarioEntity { - public MarioEnemy(double x, double y, double forceX, double forceY, boolean onGround, boolean subjectToGravity) { + public MarioEnemy(final double x, final double y, final double forceX, final double forceY, final boolean onGround, final boolean subjectToGravity) { super(x, y, forceX, forceY, onGround, subjectToGravity); } diff --git a/core/src/main/java/it/cavallium/warppi/extra/mario/MarioEntity.java b/core/src/main/java/it/cavallium/warppi/extra/mario/MarioEntity.java index 1facaf96..11cc7ded 100644 --- a/core/src/main/java/it/cavallium/warppi/extra/mario/MarioEntity.java +++ b/core/src/main/java/it/cavallium/warppi/extra/mario/MarioEntity.java @@ -11,7 +11,7 @@ public class MarioEntity { public boolean collisionRight; public boolean subjectToGravity; - public MarioEntity(double x, double y, double forceX, double forceY, boolean onGround, boolean subjectToGravity) { + public MarioEntity(final double x, final double y, final double forceX, final double forceY, final boolean onGround, final boolean subjectToGravity) { this.x = x; this.y = y; this.forceX = forceX; @@ -20,12 +20,12 @@ public class MarioEntity { this.subjectToGravity = subjectToGravity; } - public void setPosition(double x, double y) { + public void setPosition(final double x, final double y) { this.x = x; this.y = y; } - public void setPosition(double x, double y, boolean onGround) { + public void setPosition(final double x, final double y, final boolean onGround) { this.x = x; this.y = y; collisionDown = onGround; @@ -43,43 +43,41 @@ public class MarioEntity { return collisionDown; } - public void setOnGround(boolean onGround) { + public void setOnGround(final boolean onGround) { collisionDown = onGround; } - public void gameTick(double dt) { + public void gameTick(final double dt) { x = computeFutureDX(dt); y = computeFutureDY(dt); forceX = computeFutureForceDX(dt); forceY = computeFutureForceDY(dt); } - public double computeFutureDX(double dt) { - return (x + dt * forceX) - x; + public double computeFutureDX(final double dt) { + return x + dt * forceX - x; } - public double computeFutureDY(double dt) { + public double computeFutureDY(final double dt) { final double forceY = this.forceY; double y = this.y; - if (!collisionDown) { + if (!collisionDown) y += dt * forceY; - } return y - this.y; } - public double computeFutureForceDX(double dt) { + public double computeFutureForceDX(final double dt) { double forceX = this.forceX; forceX *= 0.75; return forceX - this.forceX; } - public double computeFutureForceDY(double dt) { + public double computeFutureForceDY(final double dt) { double forceY = this.forceY; - if (subjectToGravity && !collisionDown) { + if (subjectToGravity && !collisionDown) forceY -= dt * 1569.6 / 16f; - } else { + else forceY *= 0.75; - } return forceY - this.forceY; } } diff --git a/core/src/main/java/it/cavallium/warppi/extra/mario/MarioGame.java b/core/src/main/java/it/cavallium/warppi/extra/mario/MarioGame.java index f799669f..056868fd 100644 --- a/core/src/main/java/it/cavallium/warppi/extra/mario/MarioGame.java +++ b/core/src/main/java/it/cavallium/warppi/extra/mario/MarioGame.java @@ -26,15 +26,15 @@ public class MarioGame { canMove = true; } - public MarioBlock getBlockAt(int x, int y) { + public MarioBlock getBlockAt(final int x, final int y) { return worlds[currentWorld].getBlockAt(x, y); } - public MarioBlock getBlockAt(double x, double y) { + public MarioBlock getBlockAt(final double x, final double y) { return getBlockAt((int) x, (int) y); } - public void move(float dt, double deltaX, double deltaY) { + public void move(final float dt, final double deltaX, final double deltaY) { final double curX = player.getX(); final double curY = player.getY(); final double futureX = curX + deltaX; @@ -50,15 +50,14 @@ public class MarioGame { return worlds[currentWorld]; } - public void gameTick(float dt, boolean upPressed, boolean downPressed, boolean leftPressed, boolean rightPressed, - boolean jumpPressed, boolean runPressed) { + public void gameTick(final float dt, final boolean upPressed, final boolean downPressed, final boolean leftPressed, + final boolean rightPressed, final boolean jumpPressed, final boolean runPressed) { checkOnGround(getPlayer(), dt); checkCollisionTop(getPlayer(), dt); checkCollisionLeft(getPlayer(), dt); checkCollisionRight(getPlayer(), dt); - if (canMove) { + if (canMove) move(dt, (rightPressed ? 1 : 0) - (leftPressed ? 1 : 0), jumpPressed ? 1 : 0); - } getPlayer().gameTick(dt); final MarioWorld w = getCurrentWorld(); @@ -72,25 +71,24 @@ public class MarioGame { } @SuppressWarnings("unused") - private int nearest(double val, int a, int b) { + private int nearest(final double val, final int a, final int b) { final double aa = Math.abs(val - a); final double ab = Math.abs(val - b); - if (aa < ab) { + if (aa < ab) return (int) aa; - } else { + else return (int) ab; - } } - private void checkOnGround(MarioEntity e, float dt) { + private void checkOnGround(final MarioEntity e, final float dt) { if (e.subjectToGravity) { final int xA = (int) Math.floor(e.getX()); final int xB = (int) Math.ceil(e.getX()); final int y0 = (int) Math.ceil(e.getY()); final int y1 = (int) Math.ceil(e.getY() + e.computeFutureDY(dt)); boolean onGround = false; - if (y1 < y0) { - for (int y = y0; y >= y1; y--) { + if (y1 < y0) + for (int y = y0; y >= y1; y--) for (int x = xA; x <= xB; x++) { final byte b = getCurrentWorld().getBlockIdAt(x, y - 1); if (MarioBlock.isSolid(b)) { @@ -103,8 +101,7 @@ public class MarioGame { break; } } - } - } else { + else for (int x = xA; x <= xB; x++) { final byte b = getCurrentWorld().getBlockIdAt(x, y0 - 1); if (MarioBlock.isSolid(b)) { @@ -116,22 +113,20 @@ public class MarioGame { } } } - } - if (!onGround) { + if (!onGround) e.setOnGround(false); - } } } - private void checkCollisionTop(MarioEntity e, float dt) { + private void checkCollisionTop(final MarioEntity e, final float dt) { if (e.subjectToGravity) { final int xA = (int) Math.floor(e.getX()); final int xB = (int) Math.ceil(e.getX()); final int y0 = (int) Math.ceil(e.getY()); final int y1 = (int) Math.ceil(e.getY() + e.computeFutureDY(dt)); boolean collisionUp = false; - if (y1 > y0) { - for (int y = y0; y <= y1; y++) { + if (y1 > y0) + for (int y = y0; y <= y1; y++) for (int x = xA; x <= xB; x++) { final byte b = getCurrentWorld().getBlockIdAt(x, y + 1); if (MarioBlock.isSolid(b)) { @@ -144,8 +139,7 @@ public class MarioGame { break; } } - } - } else { + else for (int x = xA; x <= xB; x++) { final byte b = getCurrentWorld().getBlockIdAt(x, y0 + 1); if (MarioBlock.isSolid(b)) { @@ -157,14 +151,12 @@ public class MarioGame { } } } - } - if (!collisionUp) { + if (!collisionUp) e.collisionUp = false; - } } } - private void checkCollisionRight(MarioEntity e, float dt) { + private void checkCollisionRight(final MarioEntity e, final float dt) { if (e.subjectToGravity) { final int yA = (int) Math.floor(e.getY()); final int yB = (int) Math.ceil(e.getY()); @@ -172,8 +164,8 @@ public class MarioGame { final double x1double = e.getX() + e.computeFutureDX(dt); final int x1 = (int) Math.floor(x1double); boolean collisionRight = false; - if (x1 > x0) { - for (int x = x0; x <= x1; x++) { + if (x1 > x0) + for (int x = x0; x <= x1; x++) for (int y = yA; y <= yB; y++) { final byte b = getCurrentWorld().getBlockIdAt(x + 1, y); if (MarioBlock.isSolid(b)) { @@ -186,8 +178,7 @@ public class MarioGame { break; } } - } - } else { + else for (int y = yA; y <= yB; y++) { final byte b = getCurrentWorld().getBlockIdAt(x0 + 1, y); if (MarioBlock.isSolid(b)) { @@ -199,14 +190,12 @@ public class MarioGame { } } } - } - if (!collisionRight) { + if (!collisionRight) e.collisionRight = false; - } } } - private void checkCollisionLeft(MarioEntity e, float dt) { + private void checkCollisionLeft(final MarioEntity e, final float dt) { if (e.subjectToGravity) { final int yA = (int) Math.floor(e.getY()); final int yB = (int) Math.ceil(e.getY()); @@ -220,39 +209,34 @@ public class MarioGame { e.setPosition(0, e.getY()); } e.collisionLeft = true; - } else { - if (x1 < x0) { - for (int x = x0; x >= x1; x--) { - for (int y = yA; y <= yB; y++) { - final byte b = getCurrentWorld().getBlockIdAt(x - 1, y); - if (MarioBlock.isSolid(b)) { - collisionLeft = true; - if (e.forceX < 0 && x1double <= x) { - e.forceX = 0; - e.setPosition(x, e.getY()); - e.collisionLeft = true; - } - break; - } - } - } - } else { + } else if (x1 < x0) + for (int x = x0; x >= x1; x--) for (int y = yA; y <= yB; y++) { - final byte b = getCurrentWorld().getBlockIdAt(x0 - 1, y); + final byte b = getCurrentWorld().getBlockIdAt(x - 1, y); if (MarioBlock.isSolid(b)) { collisionLeft = true; - if (e.forceX < 0 && x1double <= x0) { + if (e.forceX < 0 && x1double <= x) { e.forceX = 0; - e.setPosition(x0, e.getY()); + e.setPosition(x, e.getY()); e.collisionLeft = true; } + break; + } + } + else + for (int y = yA; y <= yB; y++) { + final byte b = getCurrentWorld().getBlockIdAt(x0 - 1, y); + if (MarioBlock.isSolid(b)) { + collisionLeft = true; + if (e.forceX < 0 && x1double <= x0) { + e.forceX = 0; + e.setPosition(x0, e.getY()); + e.collisionLeft = true; } } } - } - if (!collisionLeft) { + if (!collisionLeft) e.collisionLeft = false; - } } } diff --git a/core/src/main/java/it/cavallium/warppi/extra/mario/MarioWorld.java b/core/src/main/java/it/cavallium/warppi/extra/mario/MarioWorld.java index e6cae610..1146233c 100644 --- a/core/src/main/java/it/cavallium/warppi/extra/mario/MarioWorld.java +++ b/core/src/main/java/it/cavallium/warppi/extra/mario/MarioWorld.java @@ -17,7 +17,7 @@ public class MarioWorld { * @param events * @param marioEnemies */ - public MarioWorld(int[] spawnPoint, int width, int height, byte[][] data, MarioEvent[] events, MarioEntity[] entities) { + public MarioWorld(final int[] spawnPoint, final int width, final int height, final byte[][] data, final MarioEvent[] events, final MarioEntity[] entities) { this.spawnPoint = spawnPoint; this.width = width; this.height = height; @@ -26,19 +26,17 @@ public class MarioWorld { this.entities = entities; } - public byte getBlockIdAt(int x, int y) { - final int idy = (height - 1 - y); - if (idy < 0 || idy >= data.length) { + public byte getBlockIdAt(final int x, final int y) { + final int idy = height - 1 - y; + if (idy < 0 || idy >= data.length) return 0b0; - } final int idx = x; - if (idx < 0 || idx >= data[0].length) { + if (idx < 0 || idx >= data[0].length) return 0b0; - } return data[idy][idx]; } - public MarioBlock getBlockAt(int x, int y) { + public MarioBlock getBlockAt(final int x, final int y) { return new MarioBlock(x, y, getBlockIdAt(x, y)); } diff --git a/core/src/main/java/it/cavallium/warppi/extra/mario/PlayerEntity.java b/core/src/main/java/it/cavallium/warppi/extra/mario/PlayerEntity.java index 1056952c..e07cb327 100644 --- a/core/src/main/java/it/cavallium/warppi/extra/mario/PlayerEntity.java +++ b/core/src/main/java/it/cavallium/warppi/extra/mario/PlayerEntity.java @@ -14,13 +14,13 @@ public class PlayerEntity extends MarioEntity { private double controllerDX; private double controllerDY; - public PlayerEntity(double x, double y, int life) { + public PlayerEntity(final double x, final double y, final int life) { super(x, y, 0, 0, true, true); this.life = life; } @Override - public void gameTick(double dt) { + public void gameTick(final double dt) { walkAnimation += dt; x += computeFutureDX(dt); y += computeFutureDY(dt); @@ -48,87 +48,79 @@ public class PlayerEntity extends MarioEntity { if (jumptime <= 0.5f && !jumping && collisionDown) { jumping = true; collisionDown = false; - } else if (jumptime <= 0.5f) {} else { + } else if (jumptime <= 0.5f) {} else jumping = false; - } } else { jumping = false; - if (collisionDown) { + if (collisionDown) jumptime = 0; - } else { + else jumptime = Float.MAX_VALUE; - } } if (!walking & !running & !jumping) { marioSkinPos[0] = 0; marioSkinPos[1] = 0; - } else if (collisionDown & walking & !running & !jumping && walkAnimation >= 0.08) { + } else if (collisionDown & walking & !running & !jumping && walkAnimation >= 0.08) while (walkAnimation > 0.08) { walkAnimation -= 0.08; - if (marioSkinPos[0] == 1 & marioSkinPos[1] == 0) { + if (marioSkinPos[0] == 1 & marioSkinPos[1] == 0) marioSkinPos[0] += 2; - } else if (marioSkinPos[0] == 3 & marioSkinPos[1] == 0) { + else if (marioSkinPos[0] == 3 & marioSkinPos[1] == 0) marioSkinPos[0] -= 1; - } else if (marioSkinPos[0] == 2 & marioSkinPos[1] == 0) { + else if (marioSkinPos[0] == 2 & marioSkinPos[1] == 0) marioSkinPos[0] -= 1; - } else { + else { marioSkinPos[0] = 1; marioSkinPos[1] = 0; } } - } else if (jumping) { + else if (jumping) { marioSkinPos[0] = 5; marioSkinPos[1] = 1; } } @Override - public double computeFutureDX(double dt) { + public double computeFutureDX(final double dt) { return super.computeFutureDX(dt); } - public double computeFuturedDY(double dt) { + public double computeFuturedDY(final double dt) { return super.computeFutureDY(dt); } @Override - public double computeFutureForceDX(double dt) { + public double computeFutureForceDX(final double dt) { double forceX = this.forceX; if (controllerDX == 0) {} else { - if (controllerDX > 0) { //RIGHT - if (forceX < 500f / 16f) { + if (controllerDX > 0) + if (forceX < 500f / 16f) forceX += dt * 500f / 16f; - } - } - if (controllerDX < 0) { //LEFT - if (forceX > -500f / 16f) { + if (controllerDX < 0) + if (forceX > -500f / 16f) forceX -= dt * 500f / 16f; - } - } } - return (forceX + super.computeFutureForceDX(dt)) - this.forceX; + return forceX + super.computeFutureForceDX(dt) - this.forceX; } @Override - public double computeFutureForceDY(double dt) { + public double computeFutureForceDY(final double dt) { float jumptime = this.jumptime; double forceY = this.forceY; if (controllerDY > 0) { //JUMP - if (collisionUp) { + if (collisionUp) jumptime = Float.MAX_VALUE; - } jumptime += dt; - if (jumptime <= 0.5f && !jumping && collisionDown) { + if (jumptime <= 0.5f && !jumping && collisionDown) forceY = dt * (4 * 1569.6f) / 16f; - } else if (jumptime <= 0.5f) { + else if (jumptime <= 0.5f) forceY = dt * (4 * 1569.6f) / 16f; - } } - return (forceY + super.computeFutureForceDY(dt)) - this.forceY; + return forceY + super.computeFutureForceDY(dt) - this.forceY; } - public void move(float dt, double dX, double dY) { + public void move(final float dt, final double dX, final double dY) { walkAnimation += dt; controllerDX = dX; diff --git a/core/src/main/java/it/cavallium/warppi/flow/BehaviorSubject.java b/core/src/main/java/it/cavallium/warppi/flow/BehaviorSubject.java index 029cf057..92817723 100644 --- a/core/src/main/java/it/cavallium/warppi/flow/BehaviorSubject.java +++ b/core/src/main/java/it/cavallium/warppi/flow/BehaviorSubject.java @@ -11,7 +11,7 @@ public class BehaviorSubject extends Subject { lastValueSet = false; } - protected BehaviorSubject(T initialValue) { + protected BehaviorSubject(final T initialValue) { super(); lastValue = initialValue; lastValueSet = true; @@ -21,31 +21,28 @@ public class BehaviorSubject extends Subject { return new BehaviorSubject<>(); } - public final static BehaviorSubject create(T initialValue) { - return new BehaviorSubject(initialValue); + public final static BehaviorSubject create(final T initialValue) { + return new BehaviorSubject<>(initialValue); } @Override public void onComplete() { - for (Subscriber sub : this.subscribers) { + for (final Subscriber sub : subscribers) sub.onComplete(); - } } @Override - public void onError(Throwable e) { - for (Subscriber sub : this.subscribers) { - sub.onError(e); - } ; + public void onError(final Throwable e) { + for (final Subscriber sub : subscribers) + sub.onError(e);; } @Override - public void onNext(T t) { + public void onNext(final T t) { lastValue = t; lastValueSet = true; - for (Subscriber sub : this.subscribers) { + for (final Subscriber sub : subscribers) sub.onNext(t); - } } @Override @@ -79,13 +76,12 @@ public class BehaviorSubject extends Subject { } @Override - public void onSubscribe(Disposable d) { + public void onSubscribe(final Disposable d) { @SuppressWarnings("unchecked") - DisposableOfSubscriber ds = (DisposableOfSubscriber) d; - Subscriber s = ds.getSubscriber(); - if (lastValueSet) { + final DisposableOfSubscriber ds = (DisposableOfSubscriber) d; + final Subscriber s = ds.getSubscriber(); + if (lastValueSet) s.onNext(lastValue); - } } public T getLastValue() { diff --git a/core/src/main/java/it/cavallium/warppi/flow/Consumer.java b/core/src/main/java/it/cavallium/warppi/flow/Consumer.java index addbb885..3eedfd1d 100644 --- a/core/src/main/java/it/cavallium/warppi/flow/Consumer.java +++ b/core/src/main/java/it/cavallium/warppi/flow/Consumer.java @@ -26,9 +26,9 @@ public interface Consumer { * @throws NullPointerException * if {@code after} is null */ - default Consumer andThen(Consumer after) { + default Consumer andThen(final Consumer after) { Objects.requireNonNull(after); - return (T t) -> { + return (final T t) -> { accept(t); after.accept(t); }; diff --git a/core/src/main/java/it/cavallium/warppi/flow/Disposable.java b/core/src/main/java/it/cavallium/warppi/flow/Disposable.java index 6e3fd6c2..5839c67c 100644 --- a/core/src/main/java/it/cavallium/warppi/flow/Disposable.java +++ b/core/src/main/java/it/cavallium/warppi/flow/Disposable.java @@ -1,7 +1,7 @@ package it.cavallium.warppi.flow; public interface Disposable { - public void dispose(); + void dispose(); - public boolean isDisposed(); + boolean isDisposed(); } diff --git a/core/src/main/java/it/cavallium/warppi/flow/IntervalsManager.java b/core/src/main/java/it/cavallium/warppi/flow/IntervalsManager.java index ae58b3f8..322ed66f 100644 --- a/core/src/main/java/it/cavallium/warppi/flow/IntervalsManager.java +++ b/core/src/main/java/it/cavallium/warppi/flow/IntervalsManager.java @@ -9,35 +9,31 @@ public class IntervalsManager { private static List intervals = new LinkedList<>(); static { - startChecker(); + IntervalsManager.startChecker(); } private IntervalsManager() { } - public static void register(ObservableInterval t) { - synchronized (intervals) { - if (!intervals.contains(t)) { - intervals.add(t); - } + public static void register(final ObservableInterval t) { + synchronized (IntervalsManager.intervals) { + if (!IntervalsManager.intervals.contains(t)) + IntervalsManager.intervals.add(t); } } private static void startChecker() { - Thread t = new Thread(() -> { + final Thread t = new Thread(() -> { try { while (true) { Thread.sleep(1000); - for (ObservableInterval interval : intervals) { - if (interval.running) { - if (interval.subscribers.size() <= 0) { + for (final ObservableInterval interval : IntervalsManager.intervals) + if (interval.running) + if (interval.subscribers.size() <= 0) interval.stopInterval(); - } - } - } } - } catch (InterruptedException e) { + } catch (final InterruptedException e) { e.printStackTrace(); } }); diff --git a/core/src/main/java/it/cavallium/warppi/flow/Observable.java b/core/src/main/java/it/cavallium/warppi/flow/Observable.java index 0146dd18..f383e320 100644 --- a/core/src/main/java/it/cavallium/warppi/flow/Observable.java +++ b/core/src/main/java/it/cavallium/warppi/flow/Observable.java @@ -14,69 +14,75 @@ public abstract class Observable implements ObservableSource { return null; } - public Disposable subscribe(Action1 onNext) { + public Disposable subscribe(final Action1 onNext) { return subscribe(createSubscriber(onNext)); } - protected Observable.DisposableOfSubscriber createDisposable(Subscriber sub) { + protected Observable.DisposableOfSubscriber createDisposable(final Subscriber sub) { return new DisposableOfSubscriber(sub); } - public Disposable subscribe(Action1 onNext, Action1 onError) { + public Disposable subscribe(final Action1 onNext, final Action1 onError) { return subscribe(createSubscriber(onNext, onError)); } - public Disposable subscribe(Action1 onNext, Action1 onError, Action0 onCompleted) { + public Disposable subscribe(final Action1 onNext, final Action1 onError, + final Action0 onCompleted) { return subscribe(createSubscriber(onNext, onError, onCompleted)); } - public void subscribe(Observer obs) { + @Override + public void subscribe(final Observer obs) { subscribe(createSubscriber(obs)); } - public Disposable subscribe(Subscriber sub) { + public Disposable subscribe(final Subscriber sub) { subscribers.add(sub); return createDisposable(sub); } - protected Subscriber createSubscriber(Action1 onNext) { + protected Subscriber createSubscriber(final Action1 onNext) { return new Subscriber() { @Override - public void onSubscribe(Subscription s) {} + public void onSubscribe(final Subscription s) {} - public void onNext(T t) { + @Override + public void onNext(final T t) { onNext.call(t); } }; } - protected Subscriber createSubscriber(Action1 onNext, Action1 onError) { + protected Subscriber createSubscriber(final Action1 onNext, final Action1 onError) { return new Subscriber() { @Override - public void onSubscribe(Subscription s) {} + public void onSubscribe(final Subscription s) {} - public void onNext(T t) { + @Override + public void onNext(final T t) { onNext.call(t); } @Override - public void onError(Throwable t) { + public void onError(final Throwable t) { onError.call(t); } }; } - protected Subscriber createSubscriber(Action1 onNext, Action1 onError, Action0 onCompl) { + protected Subscriber createSubscriber(final Action1 onNext, final Action1 onError, + final Action0 onCompl) { return new Subscriber() { @Override - public void onSubscribe(Subscription s) {} + public void onSubscribe(final Subscription s) {} - public void onNext(T t) { + @Override + public void onNext(final T t) { onNext.call(t); } @Override - public void onError(Throwable t) { + public void onError(final Throwable t) { onError.call(t); } @@ -87,17 +93,18 @@ public abstract class Observable implements ObservableSource { }; } - protected Subscriber createSubscriber(Observer obs) { + protected Subscriber createSubscriber(final Observer obs) { return new Subscriber() { @Override - public void onSubscribe(Subscription s) {} + public void onSubscribe(final Subscription s) {} - public void onNext(T t) { + @Override + public void onNext(final T t) { obs.onNext(t); } @Override - public void onError(Throwable t) { + public void onError(final Throwable t) { obs.onError(t); } @@ -108,32 +115,32 @@ public abstract class Observable implements ObservableSource { }; } - public static final Observable merge(Observable a, Observable b) { + public static final Observable merge(final Observable a, final Observable b) { return new ObservableMerged<>(a, b); } @Deprecated - public static final Observable of(Observable a) { + public static final Observable of(final Observable a) { return null; } - public final Observable map(Function f) { - return new ObservableMap(this, f); + public final Observable map(final Function f) { + return new ObservableMap<>(this, f); } - public static final Observable> combineLatest(Observable a, Observable b) { + public static final Observable> combineLatest(final Observable a, final Observable b) { return new ObservableCombinedLatest<>(a, b); } - public static final Observable> combineChanged(Observable a, Observable b) { + public static final Observable> combineChanged(final Observable a, final Observable b) { return new ObservableCombinedChanged<>(a, b); } - public static final Observable> zip(Observable a, Observable b) { + public static final Observable> zip(final Observable a, final Observable b) { return new ObservableZipped<>(a, b); } - public static final Observable interval(long interval) { + public static final Observable interval(final long interval) { return new ObservableInterval(interval); } @@ -141,7 +148,7 @@ public abstract class Observable implements ObservableSource { private final Subscriber sub; - public DisposableOfSubscriber(Subscriber sub) { + public DisposableOfSubscriber(final Subscriber sub) { this.sub = sub; } @@ -155,9 +162,8 @@ public abstract class Observable implements ObservableSource { @Override public void dispose() { - if (isDisposed()) { + if (isDisposed()) throw new RuntimeException("Already disposed!"); - } subscribers.remove(sub); Observable.this.onDisposed(sub); } @@ -169,8 +175,8 @@ public abstract class Observable implements ObservableSource { } - public Observable doOnNext(Action1 onNext) { - Subject onNextSubject = BehaviorSubject.create(); + public Observable doOnNext(final Action1 onNext) { + final Subject onNextSubject = BehaviorSubject.create(); this.subscribe((val) -> { onNext.call(val); onNextSubject.onNext(val); @@ -178,7 +184,7 @@ public abstract class Observable implements ObservableSource { return onNextSubject; } - public void onDisposed(Subscriber sub) { + public void onDisposed(final Subscriber sub) { } } diff --git a/core/src/main/java/it/cavallium/warppi/flow/ObservableCombinedChanged.java b/core/src/main/java/it/cavallium/warppi/flow/ObservableCombinedChanged.java index 6718388a..3536870f 100644 --- a/core/src/main/java/it/cavallium/warppi/flow/ObservableCombinedChanged.java +++ b/core/src/main/java/it/cavallium/warppi/flow/ObservableCombinedChanged.java @@ -4,12 +4,12 @@ import org.apache.commons.lang3.tuple.Pair; public class ObservableCombinedChanged extends Observable> { private volatile boolean initialized = false; - private Observable a; - private Observable b; + private final Observable a; + private final Observable b; private Disposable disposableA; private Disposable disposableB; - public ObservableCombinedChanged(Observable a, Observable b) { + public ObservableCombinedChanged(final Observable a, final Observable b) { super(); this.a = a; this.b = b; @@ -17,30 +17,24 @@ public class ObservableCombinedChanged extends Observable> { private void initialize() { this.disposableA = a.subscribe((t) -> { - for (Subscriber> sub : this.subscribers) { + for (final Subscriber> sub : subscribers) sub.onNext(Pair.of(t, null)); - } }, (e) -> { - for (Subscriber> sub : this.subscribers) { - sub.onError(e); - } ; + for (final Subscriber> sub : subscribers) + sub.onError(e);; }, () -> { - for (Subscriber> sub : this.subscribers) { - sub.onComplete(); - } ; + for (final Subscriber> sub : subscribers) + sub.onComplete();; }); this.disposableB = b.subscribe((t) -> { - for (Subscriber> sub : this.subscribers) { - sub.onNext(Pair.of(null, t)); - } ; + for (final Subscriber> sub : subscribers) + sub.onNext(Pair.of(null, t));; }, (e) -> { - for (Subscriber> sub : this.subscribers) { - sub.onError(e); - } ; + for (final Subscriber> sub : subscribers) + sub.onError(e);; }, () -> { - for (Subscriber> sub : this.subscribers) { - sub.onComplete(); - } ; + for (final Subscriber> sub : subscribers) + sub.onComplete();; }); } @@ -52,14 +46,14 @@ public class ObservableCombinedChanged extends Observable> { } @Override - public Disposable subscribe(Subscriber> sub) { - Disposable disp = super.subscribe(sub); + public Disposable subscribe(final Subscriber> sub) { + final Disposable disp = super.subscribe(sub); chechInitialized(); return disp; } @Override - public void onDisposed(Subscriber> sub) { + public void onDisposed(final Subscriber> sub) { super.onDisposed(sub); this.disposableA.dispose(); this.disposableB.dispose(); diff --git a/core/src/main/java/it/cavallium/warppi/flow/ObservableCombinedLatest.java b/core/src/main/java/it/cavallium/warppi/flow/ObservableCombinedLatest.java index cc15770c..991354a4 100644 --- a/core/src/main/java/it/cavallium/warppi/flow/ObservableCombinedLatest.java +++ b/core/src/main/java/it/cavallium/warppi/flow/ObservableCombinedLatest.java @@ -4,8 +4,8 @@ import org.apache.commons.lang3.tuple.Pair; public class ObservableCombinedLatest extends Observable> { private volatile boolean initialized = false; - private Observable a; - private Observable b; + private final Observable a; + private final Observable b; private Disposable disposableA; private Disposable disposableB; private volatile T lastA; @@ -13,7 +13,7 @@ public class ObservableCombinedLatest extends Observable> { private volatile boolean didAOneTime; private volatile boolean didBOneTime; - public ObservableCombinedLatest(Observable a, Observable b) { + public ObservableCombinedLatest(final Observable a, final Observable b) { super(); this.a = a; this.b = b; @@ -25,35 +25,30 @@ public class ObservableCombinedLatest extends Observable> { didAOneTime = true; receivedNext(); }, (e) -> { - for (Subscriber> sub : this.subscribers) { - sub.onError(e); - } ; + for (final Subscriber> sub : subscribers) + sub.onError(e);; }, () -> { - for (Subscriber> sub : this.subscribers) { - sub.onComplete(); - } ; + for (final Subscriber> sub : subscribers) + sub.onComplete();; }); this.disposableB = b.subscribe((t) -> { lastB = t; didBOneTime = true; receivedNext(); }, (e) -> { - for (Subscriber> sub : this.subscribers) { - sub.onError(e); - } ; + for (final Subscriber> sub : subscribers) + sub.onError(e);; }, () -> { - for (Subscriber> sub : this.subscribers) { - sub.onComplete(); - } ; + for (final Subscriber> sub : subscribers) + sub.onComplete();; }); } private void receivedNext() { - if (didAOneTime && didBOneTime) { - this.subscribers.forEach(sub -> { + if (didAOneTime && didBOneTime) + subscribers.forEach(sub -> { sub.onNext(Pair.of(lastA, lastB)); }); - } } private void chechInitialized() { @@ -64,14 +59,14 @@ public class ObservableCombinedLatest extends Observable> { } @Override - public Disposable subscribe(Subscriber> sub) { - Disposable disp = super.subscribe(sub); + public Disposable subscribe(final Subscriber> sub) { + final Disposable disp = super.subscribe(sub); chechInitialized(); return disp; } @Override - public void onDisposed(Subscriber> sub) { + public void onDisposed(final Subscriber> sub) { super.onDisposed(sub); this.disposableA.dispose(); this.disposableB.dispose(); diff --git a/core/src/main/java/it/cavallium/warppi/flow/ObservableInterval.java b/core/src/main/java/it/cavallium/warppi/flow/ObservableInterval.java index 9530ca5e..9c07a6a0 100644 --- a/core/src/main/java/it/cavallium/warppi/flow/ObservableInterval.java +++ b/core/src/main/java/it/cavallium/warppi/flow/ObservableInterval.java @@ -7,12 +7,12 @@ public class ObservableInterval extends Observable { volatile boolean running; volatile Thread timeThread; - protected ObservableInterval(long interval) { + protected ObservableInterval(final long interval) { super(); this.interval = interval; try { startInterval(); - } catch (InterruptedException e) { + } catch (final InterruptedException e) { e.printStackTrace(); } } @@ -20,15 +20,15 @@ public class ObservableInterval extends Observable { void stopInterval() { if (running) { running = false; - this.timeThread.interrupt(); + timeThread.interrupt(); } } @Override - public Disposable subscribe(Subscriber sub) { + public Disposable subscribe(final Subscriber sub) { try { startInterval(); - } catch (InterruptedException e) { + } catch (final InterruptedException e) { e.printStackTrace(); } return super.subscribe(sub); @@ -36,18 +36,16 @@ public class ObservableInterval extends Observable { void startInterval() throws InterruptedException { if (running == false) { - while (timeThread != null) { + while (timeThread != null) Thread.sleep(100); - } timeThread = new Thread(() -> { try { while (!Thread.interrupted()) { - for (Subscriber sub : this.subscribers) { + for (final Subscriber sub : subscribers) sub.onNext(System.currentTimeMillis()); - } Thread.sleep(interval); } - } catch (InterruptedException e) {} + } catch (final InterruptedException e) {} timeThread = null; }); Engine.getPlatform().setThreadName(timeThread, "ObservableTimer"); @@ -56,12 +54,12 @@ public class ObservableInterval extends Observable { } } - public static ObservableInterval create(long l) { + public static ObservableInterval create(final long l) { return new ObservableInterval(l); } @Override - public void onDisposed(Subscriber sub) { + public void onDisposed(final Subscriber sub) { super.onDisposed(sub); stopInterval(); } diff --git a/core/src/main/java/it/cavallium/warppi/flow/ObservableMap.java b/core/src/main/java/it/cavallium/warppi/flow/ObservableMap.java index 70875e74..435020f9 100644 --- a/core/src/main/java/it/cavallium/warppi/flow/ObservableMap.java +++ b/core/src/main/java/it/cavallium/warppi/flow/ObservableMap.java @@ -3,12 +3,12 @@ package it.cavallium.warppi.flow; import java.util.function.Function; public class ObservableMap extends Observable { - private Observable originalObservable; - private Function mapAction; + private final Observable originalObservable; + private final Function mapAction; private volatile boolean initialized = false; private Disposable mapDisposable; - public ObservableMap(Observable originalObservable, Function mapAction) { + public ObservableMap(final Observable originalObservable, final Function mapAction) { super(); this.originalObservable = originalObservable; this.mapAction = mapAction; @@ -16,17 +16,14 @@ public class ObservableMap extends Observable { private void initialize() { this.mapDisposable = originalObservable.subscribe((t) -> { - for (Subscriber sub : this.subscribers) { - sub.onNext(mapAction.apply(t)); - } ; + for (final Subscriber sub : subscribers) + sub.onNext(mapAction.apply(t));; }, (e) -> { - for (Subscriber sub : this.subscribers) { - sub.onError(e); - } ; + for (final Subscriber sub : subscribers) + sub.onError(e);; }, () -> { - for (Subscriber sub : this.subscribers) { - sub.onComplete(); - } ; + for (final Subscriber sub : subscribers) + sub.onComplete();; }); } @@ -38,14 +35,14 @@ public class ObservableMap extends Observable { } @Override - public Disposable subscribe(Subscriber sub) { - Disposable disp = super.subscribe(sub); + public Disposable subscribe(final Subscriber sub) { + final Disposable disp = super.subscribe(sub); chechInitialized(); return disp; } @Override - public void onDisposed(Subscriber sub) { + public void onDisposed(final Subscriber sub) { super.onDisposed(sub); mapDisposable.dispose(); } diff --git a/core/src/main/java/it/cavallium/warppi/flow/ObservableMerged.java b/core/src/main/java/it/cavallium/warppi/flow/ObservableMerged.java index 6dc60c72..b3a1a539 100644 --- a/core/src/main/java/it/cavallium/warppi/flow/ObservableMerged.java +++ b/core/src/main/java/it/cavallium/warppi/flow/ObservableMerged.java @@ -1,13 +1,13 @@ package it.cavallium.warppi.flow; public class ObservableMerged extends Observable { - private Observable originalObservableA; - private Observable originalObservableB; + private final Observable originalObservableA; + private final Observable originalObservableB; private volatile boolean initialized = false; private Disposable mapDisposableA; private Disposable mapDisposableB; - public ObservableMerged(Observable originalObservableA, Observable originalObservableB) { + public ObservableMerged(final Observable originalObservableA, final Observable originalObservableB) { super(); this.originalObservableA = originalObservableA; this.originalObservableB = originalObservableB; @@ -15,30 +15,24 @@ public class ObservableMerged extends Observable { private void initialize() { this.mapDisposableA = originalObservableA.subscribe((t) -> { - for (Subscriber sub : this.subscribers) { - sub.onNext(t); - } ; + for (final Subscriber sub : subscribers) + sub.onNext(t);; }, (e) -> { - for (Subscriber sub : this.subscribers) { - sub.onError(e); - } ; + for (final Subscriber sub : subscribers) + sub.onError(e);; }, () -> { - for (Subscriber sub : this.subscribers) { - sub.onComplete(); - } ; + for (final Subscriber sub : subscribers) + sub.onComplete();; }); this.mapDisposableB = originalObservableB.subscribe((t) -> { - for (Subscriber sub : this.subscribers) { - sub.onNext(t); - } ; + for (final Subscriber sub : subscribers) + sub.onNext(t);; }, (e) -> { - for (Subscriber sub : this.subscribers) { - sub.onError(e); - } ; + for (final Subscriber sub : subscribers) + sub.onError(e);; }, () -> { - for (Subscriber sub : this.subscribers) { - sub.onComplete(); - } ; + for (final Subscriber sub : subscribers) + sub.onComplete();; }); } @@ -50,14 +44,14 @@ public class ObservableMerged extends Observable { } @Override - public Disposable subscribe(Subscriber sub) { - Disposable disp = super.subscribe(sub); + public Disposable subscribe(final Subscriber sub) { + final Disposable disp = super.subscribe(sub); chechInitialized(); return disp; } @Override - public void onDisposed(Subscriber sub) { + public void onDisposed(final Subscriber sub) { super.onDisposed(sub); this.mapDisposableA.dispose(); this.mapDisposableB.dispose(); diff --git a/core/src/main/java/it/cavallium/warppi/flow/ObservableSource.java b/core/src/main/java/it/cavallium/warppi/flow/ObservableSource.java index 8e3a604e..b47d6f3f 100644 --- a/core/src/main/java/it/cavallium/warppi/flow/ObservableSource.java +++ b/core/src/main/java/it/cavallium/warppi/flow/ObservableSource.java @@ -1,5 +1,5 @@ package it.cavallium.warppi.flow; public interface ObservableSource { - public void subscribe(Observer observer); + void subscribe(Observer observer); } diff --git a/core/src/main/java/it/cavallium/warppi/flow/ObservableZipped.java b/core/src/main/java/it/cavallium/warppi/flow/ObservableZipped.java index 0ff45821..b6b9ede4 100644 --- a/core/src/main/java/it/cavallium/warppi/flow/ObservableZipped.java +++ b/core/src/main/java/it/cavallium/warppi/flow/ObservableZipped.java @@ -4,8 +4,8 @@ import org.apache.commons.lang3.tuple.Pair; public class ObservableZipped extends Observable> { private volatile boolean initialized = false; - private Observable a; - private Observable b; + private final Observable a; + private final Observable b; private Disposable disposableA; private Disposable disposableB; private volatile T lastA; @@ -13,7 +13,7 @@ public class ObservableZipped extends Observable> { private volatile boolean didA; private volatile boolean didB; - public ObservableZipped(Observable a, Observable b) { + public ObservableZipped(final Observable a, final Observable b) { super(); this.a = a; this.b = b; @@ -25,26 +25,22 @@ public class ObservableZipped extends Observable> { didA = true; receivedNext(); }, (e) -> { - for (Subscriber> sub : this.subscribers) { - sub.onError(e); - } ; + for (final Subscriber> sub : subscribers) + sub.onError(e);; }, () -> { - for (Subscriber> sub : this.subscribers) { - sub.onComplete(); - } ; + for (final Subscriber> sub : subscribers) + sub.onComplete();; }); this.disposableB = b.subscribe((t) -> { lastB = t; didB = true; receivedNext(); }, (e) -> { - for (Subscriber> sub : this.subscribers) { - sub.onError(e); - } ; + for (final Subscriber> sub : subscribers) + sub.onError(e);; }, () -> { - for (Subscriber> sub : this.subscribers) { - sub.onComplete(); - } ; + for (final Subscriber> sub : subscribers) + sub.onComplete();; }); } @@ -52,9 +48,8 @@ public class ObservableZipped extends Observable> { if (didA && didB) { didA = false; didB = false; - for (Subscriber> sub : this.subscribers) { - sub.onNext(Pair.of(lastA, lastB)); - } ; + for (final Subscriber> sub : subscribers) + sub.onNext(Pair.of(lastA, lastB));; } } @@ -66,14 +61,14 @@ public class ObservableZipped extends Observable> { } @Override - public Disposable subscribe(Subscriber> sub) { - Disposable disp = super.subscribe(sub); + public Disposable subscribe(final Subscriber> sub) { + final Disposable disp = super.subscribe(sub); chechInitialized(); return disp; } @Override - public void onDisposed(Subscriber> sub) { + public void onDisposed(final Subscriber> sub) { super.onDisposed(sub); this.disposableA.dispose(); this.disposableB.dispose(); diff --git a/core/src/main/java/it/cavallium/warppi/flow/Observer.java b/core/src/main/java/it/cavallium/warppi/flow/Observer.java index 7b15429a..1b4feb9d 100644 --- a/core/src/main/java/it/cavallium/warppi/flow/Observer.java +++ b/core/src/main/java/it/cavallium/warppi/flow/Observer.java @@ -1,11 +1,11 @@ package it.cavallium.warppi.flow; public interface Observer { - public void onComplete(); + void onComplete(); - public void onError(Throwable e); + void onError(Throwable e); - public void onNext(T t); + void onNext(T t); - public void onSubscribe(Disposable d); + void onSubscribe(Disposable d); } diff --git a/core/src/main/java/it/cavallium/warppi/flow/SimpleSubject.java b/core/src/main/java/it/cavallium/warppi/flow/SimpleSubject.java index 171130aa..a398c83e 100644 --- a/core/src/main/java/it/cavallium/warppi/flow/SimpleSubject.java +++ b/core/src/main/java/it/cavallium/warppi/flow/SimpleSubject.java @@ -10,23 +10,20 @@ public class SimpleSubject extends Subject { @Override public void onComplete() { - for (Subscriber sub : this.subscribers) { - sub.onComplete(); - } ; + for (final Subscriber sub : subscribers) + sub.onComplete();; } @Override - public void onError(Throwable e) { - for (Subscriber sub : this.subscribers) { - sub.onError(e); - } ; + public void onError(final Throwable e) { + for (final Subscriber sub : subscribers) + sub.onError(e);; } @Override - public void onNext(T t) { - for (Subscriber sub : this.subscribers) { - sub.onNext(t); - } ; + public void onNext(final T t) { + for (final Subscriber sub : subscribers) + sub.onNext(t);; } @Override @@ -60,6 +57,6 @@ public class SimpleSubject extends Subject { } @Override - public void onSubscribe(Disposable d) {} + public void onSubscribe(final Disposable d) {} } diff --git a/core/src/main/java/it/cavallium/warppi/flow/Subject.java b/core/src/main/java/it/cavallium/warppi/flow/Subject.java index 112eab0d..cdae202f 100644 --- a/core/src/main/java/it/cavallium/warppi/flow/Subject.java +++ b/core/src/main/java/it/cavallium/warppi/flow/Subject.java @@ -12,29 +12,30 @@ public abstract class Subject extends Observable implements Observer { abstract Subject toSerialized(); @Override - public Disposable subscribe(Action1 onNext) { + public Disposable subscribe(final Action1 onNext) { return subscribe(createSubscriber(onNext)); } @Override - public Disposable subscribe(Action1 onNext, Action1 onError) { + public Disposable subscribe(final Action1 onNext, final Action1 onError) { return subscribe(createSubscriber(onNext, onError)); } @Override - public Disposable subscribe(Action1 onNext, Action1 onError, Action0 onCompl) { + public Disposable subscribe(final Action1 onNext, final Action1 onError, + final Action0 onCompl) { return subscribe(createSubscriber(onNext, onError, onCompl)); } @Override - public void subscribe(Observer obs) { + public void subscribe(final Observer obs) { subscribe(createSubscriber(obs)); } @Override - public Disposable subscribe(Subscriber sub) { - Disposable disp = super.subscribe(sub); - this.onSubscribe(disp); + public Disposable subscribe(final Subscriber sub) { + final Disposable disp = super.subscribe(sub); + onSubscribe(disp); return disp; } } diff --git a/core/src/main/java/it/cavallium/warppi/flow/Subscriber.java b/core/src/main/java/it/cavallium/warppi/flow/Subscriber.java index 4d743007..af44e383 100644 --- a/core/src/main/java/it/cavallium/warppi/flow/Subscriber.java +++ b/core/src/main/java/it/cavallium/warppi/flow/Subscriber.java @@ -3,7 +3,7 @@ package it.cavallium.warppi.flow; public interface Subscriber { default void onComplete() {} - default void onError(Throwable t) {} + default void onError(final Throwable t) {} void onNext(T t); diff --git a/core/src/main/java/it/cavallium/warppi/flow/TestFlow.java b/core/src/main/java/it/cavallium/warppi/flow/TestFlow.java index 66b51c91..98973f64 100644 --- a/core/src/main/java/it/cavallium/warppi/flow/TestFlow.java +++ b/core/src/main/java/it/cavallium/warppi/flow/TestFlow.java @@ -3,12 +3,12 @@ package it.cavallium.warppi.flow; import org.apache.commons.lang3.tuple.Pair; public class TestFlow { - public static void main(String[] args) { + public static void main(final String[] args) { try { - BehaviorSubject subject0 = BehaviorSubject.create(0f); + final BehaviorSubject subject0 = BehaviorSubject.create(0f); - Disposable s00 = subject0.subscribe((val) -> { + final Disposable s00 = subject0.subscribe((val) -> { System.out.println(val); }); Thread.sleep(100); @@ -25,9 +25,9 @@ public class TestFlow { subject0.onComplete(); System.out.println("items sent."); - Subject subject1 = BehaviorSubject.create(0f); + final Subject subject1 = BehaviorSubject.create(0f); - Disposable s01 = subject1.map((val) -> val + 1).subscribe((val) -> { + final Disposable s01 = subject1.map((val) -> val + 1).subscribe((val) -> { System.out.println(val); }); Thread.sleep(100); @@ -44,11 +44,11 @@ public class TestFlow { subject1.onComplete(); System.out.println("items sent."); - BehaviorSubject subjectA = BehaviorSubject.create(); - BehaviorSubject subjectB = BehaviorSubject.create(); - Observable observable = Observable.merge(subjectA, subjectB); + final BehaviorSubject subjectA = BehaviorSubject.create(); + final BehaviorSubject subjectB = BehaviorSubject.create(); + final Observable observable = Observable.merge(subjectA, subjectB); - Disposable s1 = observable.subscribe((val) -> { + final Disposable s1 = observable.subscribe((val) -> { System.out.println(val); }); Thread.sleep(100); @@ -67,11 +67,11 @@ public class TestFlow { Thread.sleep(100); System.out.println("no more news subscribers left, closing publisher.."); - BehaviorSubject subjectC = BehaviorSubject.create(); - BehaviorSubject subjectD = BehaviorSubject.create(); - Observable> observableCombined = Observable.combineLatest(subjectC, subjectD); + final BehaviorSubject subjectC = BehaviorSubject.create(); + final BehaviorSubject subjectD = BehaviorSubject.create(); + final Observable> observableCombined = Observable.combineLatest(subjectC, subjectD); System.out.println("Combined observable: " + observableCombined.toString()); - Disposable s2 = observableCombined.subscribe((val) -> { + final Disposable s2 = observableCombined.subscribe((val) -> { System.out.println(val); }); Thread.sleep(100); @@ -89,8 +89,8 @@ public class TestFlow { subjectC.onComplete(); System.out.println("items sent."); - ObservableInterval timA = ObservableInterval.create(100L); - Disposable d = timA.subscribe((t) -> { + final ObservableInterval timA = ObservableInterval.create(100L); + final Disposable d = timA.subscribe((t) -> { System.out.println(t); }); @@ -98,11 +98,11 @@ public class TestFlow { d.dispose(); System.out.println("items sent."); - ObservableInterval subjectE = ObservableInterval.create(100L); - BehaviorSubject subjectF = BehaviorSubject.create(); - Observable> observableZipped = Observable.zip(subjectE, subjectF); + final ObservableInterval subjectE = ObservableInterval.create(100L); + final BehaviorSubject subjectF = BehaviorSubject.create(); + final Observable> observableZipped = Observable.zip(subjectE, subjectF); System.out.println("Zipped observable: " + observableZipped.toString()); - Disposable s3 = observableZipped.subscribe((val) -> { + final Disposable s3 = observableZipped.subscribe((val) -> { System.out.println(val); }); Thread.sleep(100); @@ -127,7 +127,7 @@ public class TestFlow { subjectF.onComplete(); System.out.println("items sent."); - } catch (Exception ex) { + } catch (final Exception ex) { ex.printStackTrace(); } } diff --git a/core/src/main/java/it/cavallium/warppi/gui/CalculatorHUD.java b/core/src/main/java/it/cavallium/warppi/gui/CalculatorHUD.java index 93d1c9dc..038d8112 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/CalculatorHUD.java +++ b/core/src/main/java/it/cavallium/warppi/gui/CalculatorHUD.java @@ -48,43 +48,22 @@ public class CalculatorHUD extends HUD { renderer.glDrawLine(0, 20, engine.getWidth() - 1, 20); renderer.glColor3i(255, 255, 255); guiSkin.use(engine); - if (Keyboard.shift) { + if (Keyboard.shift) renderer.glFillRect(2 + 18 * 0, 2, 16, 16, 16 * 2, 16 * 0, 16, 16); - } else { + else renderer.glFillRect(2 + 18 * 0, 2, 16, 16, 16 * 3, 16 * 0, 16, 16); - } - if (Keyboard.alpha) { + if (Keyboard.alpha) renderer.glFillRect(2 + 18 * 1, 2, 16, 16, 16 * 0, 16 * 0, 16, 16); - } else { + else renderer.glFillRect(2 + 18 * 1, 2, 16, 16, 16 * 1, 16 * 0, 16, 16); - } - /* - if (Calculator.angleMode == AngleMode.DEG) { - drawSkinPart(8 + 18 * 2, 2, 16 * 4, 16 * 0, 16 + 16 * 4, 16 + 16 * 0); - drawSkinPart(8 + 18 * 3, 2, 16 * 7, 16 * 0, 16 + 16 * 7, 16 + 16 * 0); - drawSkinPart(8 + 18 * 4, 2, 16 * 9, 16 * 0, 16 + 16 * 9, 16 + 16 * 0); - } else if (Calculator.angleMode == AngleMode.RAD) { - drawSkinPart(8 + 18 * 2, 2, 16 * 5, 16 * 0, 16 + 16 * 5, 16 + 16 * 0); - drawSkinPart(8 + 18 * 3, 2, 16 * 6, 16 * 0, 16 + 16 * 6, 16 + 16 * 0); - drawSkinPart(8 + 18 * 4, 2, 16 * 9, 16 * 0, 16 + 16 * 9, 16 + 16 * 0); - } else if (Calculator.angleMode == AngleMode.GRA) { - drawSkinPart(8 + 18 * 2, 2, 16 * 5, 16 * 0, 16 + 16 * 5, 16 + 16 * 0); - drawSkinPart(8 + 18 * 3, 2, 16 * 7, 16 * 0, 16 + 16 * 7, 16 + 16 * 0); - drawSkinPart(8 + 18 * 4, 2, 16 * 8, 16 * 0, 16 + 16 * 8, 16 + 16 * 0); - } else { - drawSkinPart(8 + 18 * 2, 2, 16 * 5, 16 * 0, 16 + 16 * 5, 16 + 16 * 0); - drawSkinPart(8 + 18 * 3, 2, 16 * 7, 16 * 0, 16 + 16 * 7, 16 + 16 * 0); - drawSkinPart(8 + 18 * 4, 2, 16 * 9, 16 * 0, 16 + 16 * 9, 16 + 16 * 0); - }*/ int padding = 2; - final int brightness = (int) (Math.ceil(Engine.INSTANCE.getHardwareDevice().getDisplayManager().getBrightness() * 9)); - if (brightness <= 10) { + final int brightness = (int) Math.ceil(Engine.INSTANCE.getHardwareDevice().getDisplayManager().getBrightness() * 9); + if (brightness <= 10) renderer.glFillRect(StaticVars.screenSize[0] - (padding + 16), 2, 16, 16, 16 * brightness, 16 * 1, 16, 16); - } else { + else Engine.getPlatform().getConsoleUtils().out().println(1, "Brightness error"); - } padding += 18 + 6; @@ -96,15 +75,14 @@ public class CalculatorHUD extends HUD { padding += 18 + 6; } - if (canGoBack && canGoForward) { + if (canGoBack && canGoForward) renderer.glFillRect(StaticVars.screenSize[0] - (padding + 16), 2, 16, 16, 16 * 14, 16 * 0, 16, 16); - } else if (canGoBack) { + else if (canGoBack) renderer.glFillRect(StaticVars.screenSize[0] - (padding + 16), 2, 16, 16, 16 * 15, 16 * 0, 16, 16); - } else if (canGoForward) { + else if (canGoForward) renderer.glFillRect(StaticVars.screenSize[0] - (padding + 16), 2, 16, 16, 16 * 16, 16 * 0, 16, 16); - } else { + else renderer.glFillRect(StaticVars.screenSize[0] - (padding + 16), 2, 16, 16, 16 * 17, 16 * 0, 16, 16); - } padding += 18; @@ -123,7 +101,7 @@ public class CalculatorHUD extends HUD { } @Override - public void beforeRender(float dt) { + public void beforeRender(final float dt) { // TODO Auto-generated method stub } diff --git a/core/src/main/java/it/cavallium/warppi/gui/DisplayManager.java b/core/src/main/java/it/cavallium/warppi/gui/DisplayManager.java index 06ba4ba5..74d901bc 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/DisplayManager.java +++ b/core/src/main/java/it/cavallium/warppi/gui/DisplayManager.java @@ -51,12 +51,12 @@ public final class DisplayManager implements RenderingLoop { */ public boolean forceRefresh; - public DisplayManager(HardwareDisplay monitor, HUD hud, Screen screen, String title) { + public DisplayManager(final HardwareDisplay monitor, final HUD hud, final Screen screen, final String title) { this.monitor = monitor; this.hud = hud; - this.initialTitle = title; - this.initialScreen = screen; - + initialTitle = title; + initialScreen = screen; + screenChange = Engine.getPlatform().newSemaphore(); engine = chooseGraphicEngine(); supportsPauses = engine.doesRefreshPauses(); @@ -72,9 +72,8 @@ public final class DisplayManager implements RenderingLoop { try { hud.d = this; hud.create(); - if (!hud.initialized) { + if (!hud.initialized) hud.initialize(); - } } catch (final Exception e) { e.printStackTrace(); Engine.getPlatform().exit(0); @@ -97,18 +96,18 @@ public final class DisplayManager implements RenderingLoop { * skin_tex = glGenTextures(); * glBindTexture(GL_TEXTURE_2D, skin_tex); * glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - * + * * InputStream in = new FileInputStream("skin.png"); * PNGDecoder decoder = new PNGDecoder(in); - * + * * System.out.println("width="+decoder.getWidth()); * System.out.println("height="+decoder.getHeight()); - * + * * ByteBuffer buf = * ByteBuffer.allocateDirect(4*decoder.getWidth()*decoder.getHeight()); * decoder.decode(buf, decoder.getWidth()*4, Format.RGBA); * buf.flip(); - * + * * skin = buf; * skin_w = decoder.getWidth(); * skin_h = decoder.getHeight(); @@ -165,55 +164,48 @@ public final class DisplayManager implements RenderingLoop { throw new UnsupportedOperationException("No graphic engines available."); } - public void setScreen(Screen screen) { - if (screen.initialized == false) { + public void setScreen(final Screen screen) { + if (screen.initialized == false) if (screen.canBeInHistory) { - if (this.currentSession > 0) { - final int sl = this.sessions.length + 5; //TODO: I don't know why if i don't add +5 or more some items disappear - this.sessions = Arrays.copyOfRange(this.sessions, this.currentSession, sl); + if (currentSession > 0) { + final int sl = sessions.length + 5; //TODO: I don't know why if i don't add +5 or more some items disappear + sessions = Arrays.copyOfRange(sessions, currentSession, sl); } - this.currentSession = 0; - for (int i = this.sessions.length - 1; i >= 1; i--) { - this.sessions[i] = this.sessions[i - 1]; - } - this.sessions[0] = screen; - } else { - this.currentSession = -1; - } - } + currentSession = 0; + for (int i = sessions.length - 1; i >= 1; i--) + sessions[i] = sessions[i - 1]; + sessions[0] = screen; + } else + currentSession = -1; screen.d = this; try { screen.create(); this.screen = screen; screenChange.release(); - if (screen.initialized == false) { + if (screen.initialized == false) screen.initialize(); - } } catch (final Exception e) { e.printStackTrace(); Engine.getPlatform().exit(0); } } - public void replaceScreen(Screen screen) { - if (screen.initialized == false) { - if (screen.canBeInHistory) { - this.sessions[this.currentSession] = screen; - } else { - this.currentSession = -1; - for (int i = 0; i < this.sessions.length - 2; i++) { - this.sessions[i] = this.sessions[i + 1]; - } + public void replaceScreen(final Screen screen) { + if (screen.initialized == false) + if (screen.canBeInHistory) + sessions[currentSession] = screen; + else { + currentSession = -1; + for (int i = 0; i < sessions.length - 2; i++) + sessions[i] = sessions[i + 1]; } - } screen.d = this; try { screen.create(); this.screen = screen; screenChange.release(); - if (screen.initialized == false) { + if (screen.initialized == false) screen.initialize(); - } } catch (final Exception e) { e.printStackTrace(); Engine.getPlatform().exit(0); @@ -221,65 +213,55 @@ public final class DisplayManager implements RenderingLoop { } public boolean canGoBack() { - if (this.currentSession == -1) { - return this.sessions[0] != null; - } - if (this.screen != this.sessions[this.currentSession]) { + if (currentSession == -1) + return sessions[0] != null; + if (screen != sessions[currentSession]) { - } else if (this.currentSession + 1 < this.sessions.length) { - if (this.sessions[this.currentSession + 1] != null) { + } else if (currentSession + 1 < sessions.length) { + if (sessions[currentSession + 1] != null) { - } else { + } else return false; - } - } else { + } else return false; - } - if (this.sessions[this.currentSession] != null) { + if (sessions[currentSession] != null) return true; - } return false; } public void goBack() { if (canGoBack()) { - if (this.currentSession >= 0 && this.screen != this.sessions[this.currentSession]) {} else { - this.currentSession += 1; - } - this.screen = this.sessions[this.currentSession]; + if (currentSession >= 0 && screen != sessions[currentSession]) {} else + currentSession += 1; + screen = sessions[currentSession]; screenChange.release(); } } public boolean canGoForward() { - if (this.currentSession <= 0) { // -1 e 0 + if (currentSession <= 0) return false; - } - if (this.screen != this.sessions[this.currentSession]) { + if (screen != sessions[currentSession]) { - } else if (this.currentSession > 0) { - if (this.sessions[this.currentSession - 1] != null) { + } else if (currentSession > 0) { + if (sessions[currentSession - 1] != null) { - } else { + } else return false; - } - } else { + } else return false; - } - if (this.sessions[this.currentSession] != null) { + if (sessions[currentSession] != null) return true; - } return false; } public void goForward() { if (canGoForward()) { - if (this.screen != this.sessions[this.currentSession]) { + if (screen != sessions[currentSession]) { - } else { - this.currentSession -= 1; - } - this.screen = this.sessions[this.currentSession]; + } else + currentSession -= 1; + screen = sessions[currentSession]; screenChange.release(); } } @@ -309,11 +291,9 @@ public final class DisplayManager implements RenderingLoop { private void draw_init() { if (engine.supportsFontRegistering()) { final List fontsIterator = engine.getRegisteredFonts(); - for (final BinaryFont f : fontsIterator) { - if (!f.isInitialized()) { + for (final BinaryFont f : fontsIterator) + if (!f.isInitialized()) f.initialize(engine); - } - } } renderer.glClear(engine.getWidth(), engine.getHeight()); } @@ -323,28 +303,25 @@ public final class DisplayManager implements RenderingLoop { if (error != null) { final BinaryFont fnt = Utils.getFont(false, false); - if (fnt != null && fnt != engine.getRenderer().getCurrentFont()) { + if (fnt != null && fnt != engine.getRenderer().getCurrentFont()) fnt.use(engine); - } renderer.glColor3i(129, 28, 22); renderer.glDrawStringRight(StaticVars.screenSize[0] - 2, StaticVars.screenSize[1] - (fnt.getCharacterHeight() + 2), Engine.getPlatform().getSettings().getCalculatorNameUppercase() + " CALCULATOR"); renderer.glColor3i(149, 32, 26); - renderer.glDrawStringCenter((StaticVars.screenSize[0] / 2), 22, error); + renderer.glDrawStringCenter(StaticVars.screenSize[0] / 2, 22, error); renderer.glColor3i(164, 34, 28); int i = 22; for (final String stackPart : errorStackTrace) { renderer.glDrawStringLeft(2, 22 + i, stackPart); i += 11; } - if (fonts[0] != null && fonts[0] != engine.getRenderer().getCurrentFont()) { + if (fonts[0] != null && fonts[0] != engine.getRenderer().getCurrentFont()) fonts[0].use(engine); - } renderer.glColor3i(129, 28, 22); - renderer.glDrawStringCenter((StaticVars.screenSize[0] / 2), 11, "UNEXPECTED EXCEPTION"); + renderer.glDrawStringCenter(StaticVars.screenSize[0] / 2, 11, "UNEXPECTED EXCEPTION"); } else { - if (fonts[0] != null && fonts[0] != engine.getRenderer().getCurrentFont()) { + if (fonts[0] != null && fonts[0] != engine.getRenderer().getCurrentFont()) fonts[0].use(engine); - } hud.renderBackground(); screen.render(); hud.render(); @@ -363,7 +340,7 @@ public final class DisplayManager implements RenderingLoop { @Override public void refresh() { - if (supportsPauses == false || (Keyboard.popRefreshRequest() || forceRefresh || screen.mustBeRefreshed())) { + if (supportsPauses == false || Keyboard.popRefreshRequest() || forceRefresh || screen.mustBeRefreshed()) { forceRefresh = false; draw(); } @@ -386,28 +363,26 @@ public final class DisplayManager implements RenderingLoop { Engine.getPlatform().exit(0); } - Observable workTimer = Observable.interval(tickDuration); + final Observable workTimer = Observable.interval(DisplayManager.tickDuration); - Observable onResizeObservable = engine.onResize(); + final Observable onResizeObservable = engine.onResize(); Observable> refreshObservable; - if (onResizeObservable == null) { + if (onResizeObservable == null) refreshObservable = workTimer.map((l) -> Pair.of(l, null)); - } else { + else refreshObservable = Observable.combineChanged(workTimer, engine.onResize()); - } refreshObservable.subscribe((pair) -> { double dt = 0; final long newtime = System.nanoTime(); - if (precTime == -1) { - dt = tickDuration; - } else { + if (precTime == -1) + dt = DisplayManager.tickDuration; + else dt = (newtime - precTime) / 1000d / 1000d; - } precTime = newtime; if (pair.getRight() != null) { - Integer[] windowSize = pair.getRight(); + final Integer[] windowSize = pair.getRight(); StaticVars.screenSize[0] = windowSize[0]; StaticVars.screenSize[1] = windowSize[1]; } @@ -421,26 +396,25 @@ public final class DisplayManager implements RenderingLoop { } finally {} } - public void changeBrightness(float change) { + public void changeBrightness(final float change) { setBrightness(brightness + change); } - public void setBrightness(float newval) { + public void setBrightness(final float newval) { if (newval >= 0 && newval <= 1) { brightness = newval; monitor.setBrightness(brightness); } } - public void cycleBrightness(boolean reverse) { + public void cycleBrightness(final boolean reverse) { final float step = reverse ? -0.1f : 0.1f; - if (brightness + step > 1f) { + if (brightness + step > 1f) setBrightness(0f); - } else if (brightness + step <= 0f) { + else if (brightness + step <= 0f) setBrightness(1.0f); - } else { + else changeBrightness(step); - } } public float getBrightness() { @@ -451,7 +425,7 @@ public final class DisplayManager implements RenderingLoop { public Screen[] sessions = new Screen[5]; @Deprecated - public void colore(float f1, float f2, float f3, float f4) { + public void colore(final float f1, final float f2, final float f3, final float f4) { renderer.glColor4f(f1, f2, f3, f4); } @@ -460,7 +434,7 @@ public final class DisplayManager implements RenderingLoop { } @Deprecated - public void drawSkinPart(int x, int y, int uvX, int uvY, int uvX2, int uvY2) { + public void drawSkinPart(final int x, final int y, final int uvX, final int uvY, final int uvX2, final int uvY2) { renderer.glFillRect(x, y, uvX2 - uvX, uvY2 - uvY, uvX, uvY, uvX2 - uvX, uvY2 - uvY); } diff --git a/core/src/main/java/it/cavallium/warppi/gui/GUIErrorMessage.java b/core/src/main/java/it/cavallium/warppi/gui/GUIErrorMessage.java index d1f2432c..e39c7405 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/GUIErrorMessage.java +++ b/core/src/main/java/it/cavallium/warppi/gui/GUIErrorMessage.java @@ -10,17 +10,17 @@ public class GUIErrorMessage { private final String err; private final long creationTime; - public GUIErrorMessage(Error e) { + public GUIErrorMessage(final Error e) { err = e.getLocalizedMessage(); creationTime = System.currentTimeMillis(); } - public GUIErrorMessage(Exception ex) { + public GUIErrorMessage(final Exception ex) { err = ex.getLocalizedMessage(); creationTime = System.currentTimeMillis(); } - public void draw(GraphicEngine g, Renderer r, String msg) { + public void draw(final GraphicEngine g, final Renderer r, final String msg) { final int scrW = g.getWidth(); final int scrH = g.getHeight(); final int width = 200; diff --git a/core/src/main/java/it/cavallium/warppi/gui/GraphicUtils.java b/core/src/main/java/it/cavallium/warppi/gui/GraphicUtils.java index 1757d4c0..474f8f46 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/GraphicUtils.java +++ b/core/src/main/java/it/cavallium/warppi/gui/GraphicUtils.java @@ -1,20 +1,20 @@ package it.cavallium.warppi.gui; public class GraphicUtils { - public static final float sin(float rad) { - return sin[(int) (rad * radToIndex) & SIN_MASK]; + public static final float sin(final float rad) { + return GraphicUtils.sin[(int) (rad * GraphicUtils.radToIndex) & GraphicUtils.SIN_MASK]; } - public static final float cos(float rad) { - return cos[(int) (rad * radToIndex) & SIN_MASK]; + public static final float cos(final float rad) { + return GraphicUtils.cos[(int) (rad * GraphicUtils.radToIndex) & GraphicUtils.SIN_MASK]; } - public static final float sinDeg(float deg) { - return sin[(int) (deg * degToIndex) & SIN_MASK]; + public static final float sinDeg(final float deg) { + return GraphicUtils.sin[(int) (deg * GraphicUtils.degToIndex) & GraphicUtils.SIN_MASK]; } - public static final float cosDeg(float deg) { - return cos[(int) (deg * degToIndex) & SIN_MASK]; + public static final float cosDeg(final float deg) { + return GraphicUtils.cos[(int) (deg * GraphicUtils.degToIndex) & GraphicUtils.SIN_MASK]; } @SuppressWarnings("unused") @@ -36,26 +36,26 @@ public class GraphicUtils { DEG = 180.0f / (float) Math.PI; SIN_BITS = 8; - SIN_MASK = ~(-1 << SIN_BITS); - SIN_COUNT = SIN_MASK + 1; + SIN_MASK = ~(-1 << GraphicUtils.SIN_BITS); + SIN_COUNT = GraphicUtils.SIN_MASK + 1; radFull = (float) (Math.PI * 2.0); - degFull = (float) (360.0); - radToIndex = SIN_COUNT / radFull; - degToIndex = SIN_COUNT / degFull; + degFull = (float) 360.0; + radToIndex = GraphicUtils.SIN_COUNT / GraphicUtils.radFull; + degToIndex = GraphicUtils.SIN_COUNT / GraphicUtils.degFull; - sin = new float[SIN_COUNT]; - cos = new float[SIN_COUNT]; + sin = new float[GraphicUtils.SIN_COUNT]; + cos = new float[GraphicUtils.SIN_COUNT]; - for (int i = 0; i < SIN_COUNT; i++) { - sin[i] = (float) Math.sin((i + 0.5f) / SIN_COUNT * radFull); - cos[i] = (float) Math.cos((i + 0.5f) / SIN_COUNT * radFull); + for (int i = 0; i < GraphicUtils.SIN_COUNT; i++) { + GraphicUtils.sin[i] = (float) Math.sin((i + 0.5f) / GraphicUtils.SIN_COUNT * GraphicUtils.radFull); + GraphicUtils.cos[i] = (float) Math.cos((i + 0.5f) / GraphicUtils.SIN_COUNT * GraphicUtils.radFull); } // Four cardinal directions (credits: Nate) for (int i = 0; i < 360; i += 90) { - sin[(int) (i * degToIndex) & SIN_MASK] = (float) Math.sin(i * Math.PI / 180.0); - cos[(int) (i * degToIndex) & SIN_MASK] = (float) Math.cos(i * Math.PI / 180.0); + GraphicUtils.sin[(int) (i * GraphicUtils.degToIndex) & GraphicUtils.SIN_MASK] = (float) Math.sin(i * Math.PI / 180.0); + GraphicUtils.cos[(int) (i * GraphicUtils.degToIndex) & GraphicUtils.SIN_MASK] = (float) Math.cos(i * Math.PI / 180.0); } } } diff --git a/core/src/main/java/it/cavallium/warppi/gui/GraphicalElement.java b/core/src/main/java/it/cavallium/warppi/gui/GraphicalElement.java index 4542318a..9cca4f03 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/GraphicalElement.java +++ b/core/src/main/java/it/cavallium/warppi/gui/GraphicalElement.java @@ -7,24 +7,24 @@ public interface GraphicalElement { * height, line or * length. */ - public void recomputeDimensions(); + void recomputeDimensions(); /** - * + * * @return Width of the element. */ - public int getWidth(); + int getWidth(); /** - * + * * @return Height of the element. */ - public int getHeight(); + int getHeight(); /** - * + * * @return Position of the vertical alignment line of the element, relative * to itself. */ - public int getLine(); + int getLine(); } diff --git a/core/src/main/java/it/cavallium/warppi/gui/GraphicalInterface.java b/core/src/main/java/it/cavallium/warppi/gui/GraphicalInterface.java index b3a9e797..9617df37 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/GraphicalInterface.java +++ b/core/src/main/java/it/cavallium/warppi/gui/GraphicalInterface.java @@ -1,15 +1,15 @@ package it.cavallium.warppi.gui; public interface GraphicalInterface { - public void create() throws InterruptedException; + void create() throws InterruptedException; - public void initialize() throws InterruptedException; + void initialize() throws InterruptedException; - public void render(); + void render(); - public void renderTopmost(); + void renderTopmost(); - public void beforeRender(float dt); + void beforeRender(float dt); - public boolean mustBeRefreshed(); + boolean mustBeRefreshed(); } diff --git a/core/src/main/java/it/cavallium/warppi/gui/HardwareDisplay.java b/core/src/main/java/it/cavallium/warppi/gui/HardwareDisplay.java index e873b828..464ae061 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/HardwareDisplay.java +++ b/core/src/main/java/it/cavallium/warppi/gui/HardwareDisplay.java @@ -1,9 +1,9 @@ package it.cavallium.warppi.gui; public interface HardwareDisplay { - public void initialize(); + void initialize(); - public void shutdown(); + void shutdown(); - public void setBrightness(double value); + void setBrightness(double value); } diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/Caret.java b/core/src/main/java/it/cavallium/warppi/gui/expression/Caret.java index 08d0929d..2c7f4344 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/Caret.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/Caret.java @@ -8,11 +8,11 @@ public class Caret { private final int[] lastSize; private final int[] lastLocation; - public Caret(CaretState state, int pos) { + public Caret(final CaretState state, final int pos) { this(state, pos, new int[] { 0, 0 }, new int[] { 2, 5 }); } - public Caret(CaretState state, int pos, int[] lastLocation, int[] lastSize) { + public Caret(final CaretState state, final int pos, final int[] lastLocation, final int[] lastSize) { this.state = state; this.pos = pos; remaining = pos; @@ -20,7 +20,7 @@ public class Caret { this.lastSize = lastSize; } - public void skip(int i) { + public void skip(final int i) { remaining -= i; } @@ -37,20 +37,18 @@ public class Caret { } public void flipState() { - if (state == CaretState.VISIBLE_ON) { + if (state == CaretState.VISIBLE_ON) state = CaretState.VISIBLE_OFF; - } else if (state == CaretState.VISIBLE_OFF) { + else if (state == CaretState.VISIBLE_OFF) state = CaretState.VISIBLE_ON; - } } public void turnOn() { - if (state == CaretState.VISIBLE_OFF) { + if (state == CaretState.VISIBLE_OFF) state = CaretState.VISIBLE_ON; - } } - public void setPosition(int i) { + public void setPosition(final int i) { pos = i; } @@ -58,7 +56,7 @@ public class Caret { remaining = pos; } - public void setLastLocation(int x, int y) { + public void setLastLocation(final int x, final int y) { lastLocation[0] = x; lastLocation[1] = y; } @@ -67,7 +65,7 @@ public class Caret { return new int[] { lastLocation[0], lastLocation[1] }; } - public void setLastSize(int w, int h) { + public void setLastSize(final int w, final int h) { lastSize[0] = w; lastSize[1] = h; } diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/ExtraMenu.java b/core/src/main/java/it/cavallium/warppi/gui/expression/ExtraMenu.java index 253790c0..e2260359 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/ExtraMenu.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/ExtraMenu.java @@ -11,7 +11,7 @@ public abstract class ExtraMenu implements Serializable, Keyboa private static final long serialVersionUID = -6944683477814944299L; - public ExtraMenu(T block) { + public ExtraMenu(final T block) { this.block = block; this.location = new int[] { 0, 0 }; this.width = 0; @@ -29,7 +29,7 @@ public abstract class ExtraMenu implements Serializable, Keyboa public abstract void close(); - public boolean beforeRender(float delta, Caret caret) { + public boolean beforeRender(final float delta, final Caret caret) { final int[] l = caret.getLastLocation(); final int[] cs = caret.getLastSize(); location[0] = l[0] - block.getWidth() / 2 - width / 2; diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/InputContext.java b/core/src/main/java/it/cavallium/warppi/gui/expression/InputContext.java index 6205901e..caae8619 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/InputContext.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/InputContext.java @@ -16,7 +16,7 @@ public class InputContext { variableTypes.put(MathematicalSymbols.EULER_NUMBER, V_TYPE.CONSTANT); } - public InputContext(HashMap variableTypes) { + public InputContext(final HashMap variableTypes) { this.variableTypes = variableTypes; } } diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/Block.java b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/Block.java index 51757c9f..3a68f6cf 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/Block.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/Block.java @@ -17,7 +17,7 @@ public abstract class Block implements GraphicalElement { protected int line; /** - * + * * @param r * Graphic Renderer class. * @param x @@ -53,7 +53,7 @@ public abstract class Block implements GraphicalElement { public int getLine() { return line; } - + public int getCaretDeltaPositionAfterCreation() { return 1; } diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockChar.java b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockChar.java index 6edb6213..5af89cd4 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockChar.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockChar.java @@ -11,30 +11,30 @@ public class BlockChar extends Block { private final char ch; - public BlockChar(char ch) { + public BlockChar(final char ch) { this.ch = ch; recomputeDimensions(); } @Override - public void draw(GraphicEngine ge, Renderer r, int x, int y, Caret caret) { + public void draw(final GraphicEngine ge, final Renderer r, final int x, final int y, final Caret caret) { BlockContainer.getDefaultFont(small).use(ge); r.glColor(BlockContainer.getDefaultColor()); r.glDrawCharLeft(x, y, ch); } @Override - public boolean putBlock(Caret caret, Block newBlock) { + public boolean putBlock(final Caret caret, final Block newBlock) { return false; } @Override - public boolean delBlock(Caret caret) { + public boolean delBlock(final Caret caret) { return false; } @Override - public BlockReference getBlock(Caret caret) { + public BlockReference getBlock(final Caret caret) { return null; } @@ -46,7 +46,7 @@ public class BlockChar extends Block { } @Override - public void setSmall(boolean small) { + public void setSmall(final boolean small) { this.small = small; recomputeDimensions(); } @@ -61,7 +61,7 @@ public class BlockChar extends Block { } @Override - public Feature toFeature(MathContext context) { + public Feature toFeature(final MathContext context) { return new FeatureChar(getChar()); } diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockContainer.java b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockContainer.java index ce02c680..f52887de 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockContainer.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockContainer.java @@ -34,83 +34,78 @@ public class BlockContainer implements GraphicalElement { autoMinimums = true; } - public BlockContainer(boolean small) { + public BlockContainer(final boolean small) { this(small, BlockContainer.getDefaultCharWidth(small), BlockContainer.getDefaultCharHeight(small), true); autoMinimums = true; } - public BlockContainer(boolean small, ObjectArrayList content) { + public BlockContainer(final boolean small, final ObjectArrayList content) { this(small, BlockContainer.getDefaultCharWidth(small), BlockContainer.getDefaultCharHeight(small), content, true); autoMinimums = true; } - public BlockContainer(boolean small, boolean withBorder) { + public BlockContainer(final boolean small, final boolean withBorder) { this(small, BlockContainer.getDefaultCharWidth(small), BlockContainer.getDefaultCharHeight(small), withBorder); autoMinimums = true; } - public BlockContainer(boolean small, int minWidth, int minHeight, boolean withBorder) { + public BlockContainer(final boolean small, final int minWidth, final int minHeight, final boolean withBorder) { this(small, minWidth, minHeight, new ObjectArrayList<>(), withBorder); autoMinimums = false; } - public BlockContainer(boolean small, int minWidth, int minHeight, ObjectArrayList content, boolean withBorder) { + public BlockContainer(final boolean small, final int minWidth, final int minHeight, final ObjectArrayList content, final boolean withBorder) { this.small = small; this.minWidth = minWidth; this.minHeight = minHeight; this.withBorder = withBorder; - for (final Block b : content) { - if (b.isSmall() != small) { + for (final Block b : content) + if (b.isSmall() != small) b.setSmall(small); - } - } this.content = content; recomputeDimensions(); } - public void addBlock(int position, Block b) { + public void addBlock(final int position, final Block b) { addBlockUnsafe(position, b); recomputeDimensions(); } - public void addBlockUnsafe(int position, Block b) { - if (b.isSmall() != small) { + public void addBlockUnsafe(final int position, final Block b) { + if (b.isSmall() != small) b.setSmall(small); - } - if (position >= content.size()) { + if (position >= content.size()) content.add(b); - } else { + else content.add(position, b); - } } - public void appendBlock(Block b) { + public void appendBlock(final Block b) { appendBlockUnsafe(b); recomputeDimensions(); } - public void appendBlockUnsafe(Block b) { - if (b.isSmall() != small) { + public void appendBlockUnsafe(final Block b) { + if (b.isSmall() != small) b.setSmall(small); - } content.add(b); } - public void removeBlock(Block b) { + public void removeBlock(final Block b) { removeBlockUnsafe(b); recomputeDimensions(); } - public void removeBlockUnsafe(Block b) { + public void removeBlockUnsafe(final Block b) { content.remove(b); } - public void removeAt(int i) { + public void removeAt(final int i) { content.remove(i); recomputeDimensions(); } - public BlockReference getBlockAt(int i) { + public BlockReference getBlockAt(final int i) { final Block b = content.get(i); return new BlockReference<>(b, i, this); } @@ -125,7 +120,7 @@ public class BlockContainer implements GraphicalElement { } /** - * + * * @param ge * Graphic Engine class. * @param r @@ -137,16 +132,14 @@ public class BlockContainer implements GraphicalElement { * @param caret * Position of the caret. */ - public void draw(GraphicEngine ge, Renderer r, int x, int y, Caret caret) { + public void draw(final GraphicEngine ge, final Renderer r, final int x, final int y, final Caret caret) { int paddingX = 1; - if (caret.getRemaining() == 0) { - if (content.size() > 0) { + if (caret.getRemaining() == 0) + if (content.size() > 0) BlockContainer.drawCaret(ge, r, caret, small, x, y + line - content.get(0).line, content.get(0).height); - } else { + else BlockContainer.drawCaret(ge, r, caret, small, x, y, height); - } - } if (withBorder && content.size() == 0) { r.glColor(BlockContainer.getDefaultColor()); @@ -154,21 +147,19 @@ public class BlockContainer implements GraphicalElement { r.glDrawLine(x + paddingX, y, x + paddingX, y + height - 1); r.glDrawLine(x + paddingX + width - 1, y, x + paddingX + width - 1, y + height - 1); r.glDrawLine(x + paddingX, y + height - 1, x + paddingX + width - 1, y + height - 1); - } else { + } else for (final Block b : content) { caret.skip(1); b.draw(ge, r, x + paddingX, y + line - b.line, caret); paddingX += b.getWidth(); - if (caret.getRemaining() == 0) { + if (caret.getRemaining() == 0) BlockContainer.drawCaret(ge, r, caret, small, x + paddingX, y + line - b.line, b.height); - } paddingX += 1; } - } caret.skip(1); } - public boolean putBlock(Caret caret, Block newBlock) { + public boolean putBlock(final Caret caret, final Block newBlock) { boolean added = false; if (caret.getRemaining() == 0) { @@ -187,13 +178,12 @@ public class BlockContainer implements GraphicalElement { } } caret.skip(1); - if (added) { + if (added) recomputeDimensions(); - } return added; } - public boolean delBlock(Caret caret) { + public boolean delBlock(final Caret caret) { boolean removed = false; int pos = 0; @@ -202,20 +192,19 @@ public class BlockContainer implements GraphicalElement { pos++; final int deltaCaret = caret.getRemaining(); removed = removed | b.delBlock(caret); - if (caret.getRemaining() == 0 || (removed == false && deltaCaret >= 0 && caret.getRemaining() < 0)) { + if (caret.getRemaining() == 0 || removed == false && deltaCaret >= 0 && caret.getRemaining() < 0) { removeAt(pos - 1); caret.setPosition(caret.getPosition() - deltaCaret); removed = true; } } caret.skip(1); - if (removed) { + if (removed) recomputeDimensions(); - } return removed; } - public BlockReference getBlock(Caret caret) { + public BlockReference getBlock(final Caret caret) { BlockReference block = null; int pos = 0; @@ -225,10 +214,9 @@ public class BlockContainer implements GraphicalElement { final int deltaCaret = caret.getRemaining(); block = b.getBlock(caret); - if (block != null) { + if (block != null) return block; - } - if (caret.getRemaining() == 0 || (deltaCaret >= 0 && caret.getRemaining() < 0)) { + if (caret.getRemaining() == 0 || deltaCaret >= 0 && caret.getRemaining() < 0) { block = getBlockAt(pos - 1); return block; } @@ -249,29 +237,25 @@ public class BlockContainer implements GraphicalElement { final int bl = b.getLine(); final int bh = b.getHeight(); final int bh2 = bh - bl; - if (bl > l) { + if (bl > l) l = bl; - } - if (bh2 > h2) { + if (bh2 > h2) h2 = bh2; - } } - if (content.size() > 0) { + if (content.size() > 0) w -= 1; - } h = h2 + l; line = l; - if (w > minWidth) { + if (w > minWidth) width = w; - } else { + else width = minWidth; - } - if (h > minHeight) { + if (h > minHeight) height = h; - } else { + else { height = minHeight; line = height / 2; } @@ -296,53 +280,53 @@ public class BlockContainer implements GraphicalElement { private static final int[] defFontSizes = new int[4]; private static final int defColor = 0xFF000000; - public static void initializeFonts(BinaryFont big, BinaryFont small) { - defFonts[0] = big; - defFonts[1] = small; - defFontSizes[0] = big.getCharacterWidth(); - defFontSizes[1] = big.getCharacterHeight(); - defFontSizes[2] = small.getCharacterWidth(); - defFontSizes[3] = small.getCharacterHeight(); - initialized = true; + public static void initializeFonts(final BinaryFont big, final BinaryFont small) { + BlockContainer.defFonts[0] = big; + BlockContainer.defFonts[1] = small; + BlockContainer.defFontSizes[0] = big.getCharacterWidth(); + BlockContainer.defFontSizes[1] = big.getCharacterHeight(); + BlockContainer.defFontSizes[2] = small.getCharacterWidth(); + BlockContainer.defFontSizes[3] = small.getCharacterHeight(); + BlockContainer.initialized = true; } - public static BinaryFont getDefaultFont(boolean small) { - checkInitialized(); - return defFonts[small ? 1 : 0]; + public static BinaryFont getDefaultFont(final boolean small) { + BlockContainer.checkInitialized(); + return BlockContainer.defFonts[small ? 1 : 0]; } public static int getDefaultColor() { - return defColor; + return BlockContainer.defColor; } - public static int getDefaultCharWidth(boolean b) { - checkInitialized(); - return defFontSizes[b ? 2 : 0]; + public static int getDefaultCharWidth(final boolean b) { + BlockContainer.checkInitialized(); + return BlockContainer.defFontSizes[b ? 2 : 0]; } - public static int getDefaultCharHeight(boolean b) { - checkInitialized(); - return defFontSizes[b ? 3 : 1]; + public static int getDefaultCharHeight(final boolean b) { + BlockContainer.checkInitialized(); + return BlockContainer.defFontSizes[b ? 3 : 1]; } - public static void drawCaret(GraphicEngine ge, Renderer r, Caret caret, boolean small, int x, int y, int height) { + public static void drawCaret(final GraphicEngine ge, final Renderer r, final Caret caret, final boolean small, + final int x, final int y, final int height) { if (caret.getState() == CaretState.VISIBLE_ON) { - r.glColor(getDefaultColor()); + r.glColor(BlockContainer.getDefaultColor()); r.glFillColor(x, y, small ? 2 : 3, height); caret.setLastLocation(x, y); caret.setLastSize(small ? 2 : 3, height); } } - public void setSmall(boolean small) { + public void setSmall(final boolean small) { this.small = small; if (autoMinimums) { minWidth = BlockContainer.getDefaultCharWidth(small); minHeight = BlockContainer.getDefaultCharHeight(small); } - for (final Block b : content) { + for (final Block b : content) b.setSmall(small); - } recomputeDimensions(); } @@ -351,28 +335,25 @@ public class BlockContainer implements GraphicalElement { } private static void checkInitialized() { - if (!initialized) { + if (!BlockContainer.initialized) Engine.getPlatform().throwNewExceptionInInitializerError("Please initialize BlockContainer by running the method BlockContainer.initialize(...) first!"); - } } public int computeCaretMaxBound() { int maxpos = 0; - for (final Block b : content) { + for (final Block b : content) maxpos += 1 + b.computeCaretMaxBound(); - } return maxpos + 1; } - public Function toFunction(MathContext context) throws Error { + public Function toFunction(final MathContext context) throws Error { final ObjectArrayList blocks = getContent(); final ObjectArrayList blockFeatures = new ObjectArrayList<>(); for (final Block block : blocks) { final Feature blockFeature = block.toFeature(context); - if (blockFeature == null) { + if (blockFeature == null) throw new Error(Errors.NOT_IMPLEMENTED, "The block " + block.getClass().getSimpleName() + " isn't a known Block"); - } blockFeatures.add(blockFeature); } diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockDivision.java b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockDivision.java index 11509145..093ebf6c 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockDivision.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockDivision.java @@ -25,7 +25,7 @@ public class BlockDivision extends Block { } @Override - public void draw(GraphicEngine ge, Renderer r, int x, int y, Caret caret) { + public void draw(final GraphicEngine ge, final Renderer r, final int x, final int y, final Caret caret) { BlockContainer.getDefaultFont(small).use(ge); r.glColor(BlockContainer.getDefaultColor()); containerUp.draw(ge, r, x + 1 + paddingLeftUpper, y, caret); @@ -35,34 +35,31 @@ public class BlockDivision extends Block { } @Override - public boolean putBlock(Caret caret, Block newBlock) { + public boolean putBlock(final Caret caret, final Block newBlock) { boolean added = false; added = added | containerUp.putBlock(caret, newBlock); added = added | containerDown.putBlock(caret, newBlock); - if (added) { + if (added) recomputeDimensions(); - } return added; } @Override - public boolean delBlock(Caret caret) { + public boolean delBlock(final Caret caret) { boolean removed = false; removed = removed | containerUp.delBlock(caret); removed = removed | containerDown.delBlock(caret); - if (removed) { + if (removed) recomputeDimensions(); - } return removed; } @Override - public BlockReference getBlock(Caret caret) { + public BlockReference getBlock(final Caret caret) { BlockReference bl = null; bl = containerUp.getBlock(caret); - if (bl != null) { + if (bl != null) return bl; - } bl = containerDown.getBlock(caret); return bl; } @@ -92,7 +89,7 @@ public class BlockDivision extends Block { } @Override - public void setSmall(boolean small) { + public void setSmall(final boolean small) { this.small = small; containerUp.setSmall(small); containerDown.setSmall(small); @@ -113,7 +110,7 @@ public class BlockDivision extends Block { } @Override - public Feature toFeature(MathContext context) throws Error { + public Feature toFeature(final MathContext context) throws Error { final Function upper = getUpperContainer().toFunction(context); final Function lower = getLowerContainer().toFunction(context); return new FeatureDivision(upper, lower); diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockExponentialNotation.java b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockExponentialNotation.java index 5dbfb6f8..d19d4074 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockExponentialNotation.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockExponentialNotation.java @@ -9,7 +9,7 @@ public class BlockExponentialNotation extends BlockPower { private int bh; @Override - public void draw(GraphicEngine ge, Renderer r, int x, int y, Caret caret) { + public void draw(final GraphicEngine ge, final Renderer r, final int x, final int y, final Caret caret) { BlockContainer.getDefaultFont(small).use(ge); r.glColor(BlockContainer.getDefaultColor()); r.glDrawStringLeft(x, y + height - bh, "ℯ℮"); diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockLogarithm.java b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockLogarithm.java index d96d9b36..6f762dc0 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockLogarithm.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockLogarithm.java @@ -33,19 +33,18 @@ public class BlockLogarithm extends Block { recomputeDimensions(); } - public BlockLogarithm(ObjectArrayList blocks) { + public BlockLogarithm(final ObjectArrayList blocks) { containerBase = new BlockContainer(true); containerNumber = new BlockContainer(false, blocks); recomputeDimensions(); } @Override - public void draw(GraphicEngine ge, Renderer r, int x, int y, Caret caret) { + public void draw(final GraphicEngine ge, final Renderer r, final int x, final int y, final Caret caret) { BlockContainer.getDefaultFont(small).use(ge); r.glColor(BlockContainer.getDefaultColor()); - if (prefix != null) { + if (prefix != null) r.glDrawStringLeft(x + 1, y + line - chh / 2, prefix); - } r.glDrawCharLeft(x + bw + prw, y + toph, '╭'); r.glDrawCharLeft(x + bw + prw, y + toph + nmbh - chh, '╰'); if (small) { @@ -64,45 +63,41 @@ public class BlockLogarithm extends Block { } @Override - public boolean putBlock(Caret caret, Block newBlock) { + public boolean putBlock(final Caret caret, final Block newBlock) { boolean added = false; added = added | containerBase.putBlock(caret, newBlock); added = added | containerNumber.putBlock(caret, newBlock); - if (added) { + if (added) recomputeDimensions(); - } return added; } @Override - public boolean delBlock(Caret caret) { + public boolean delBlock(final Caret caret) { boolean removed = false; removed = removed | containerBase.delBlock(caret); removed = removed | containerNumber.delBlock(caret); - if (removed) { + if (removed) recomputeDimensions(); - } return removed; } @Override - public BlockReference getBlock(Caret caret) { + public BlockReference getBlock(final Caret caret) { BlockReference bl = null; bl = containerBase.getBlock(caret); - if (bl != null) { + if (bl != null) return bl; - } bl = containerNumber.getBlock(caret); return bl; } @Override public void recomputeDimensions() { - if (prefix == null) { + if (prefix == null) prw = 0; - } else { + else prw = 1 + BlockContainer.getDefaultCharWidth(small) * prefix.length(); - } bw = containerBase.getWidth(); bh = containerBase.getHeight(); bl = containerBase.getLine(); @@ -115,25 +110,23 @@ public class BlockLogarithm extends Block { if (bl > nmbh) { toph = bl - nmbh; line = toph + nl; - if (bl + (bh - bl) > toph + nmbh) { - height = bl + (bh - bl); - } else { + if (bl + bh - bl > toph + nmbh) + height = bl + bh - bl; + else height = toph + nmbh; - } } else { System.out.println("b"); toph = 0; line = toph + nl; - if (nmbh + bh - bl > toph + nmbh) { - height = nmbh + (bh - bl); - } else { + if (nmbh + bh - bl > toph + nmbh) + height = nmbh + bh - bl; + else height = toph + nmbh; - } } } @Override - public void setSmall(boolean small) { + public void setSmall(final boolean small) { this.small = small; containerBase.setSmall(small); containerNumber.setSmall(small); @@ -154,7 +147,7 @@ public class BlockLogarithm extends Block { } @Override - public Feature toFeature(MathContext context) throws Error { + public Feature toFeature(final MathContext context) throws Error { final Function base = getBaseContainer().toFunction(context); final Function number = getNumberContainer().toFunction(context); return new FeatureLogarithm(base, number); diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockNumericChar.java b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockNumericChar.java index ccb34d45..7976c2af 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockNumericChar.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockNumericChar.java @@ -2,7 +2,7 @@ package it.cavallium.warppi.gui.expression.blocks; public class BlockNumericChar extends BlockChar { - public BlockNumericChar(char ch) { + public BlockNumericChar(final char ch) { super(ch); } diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockParenthesis.java b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockParenthesis.java index 36b55f81..15c3bf8e 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockParenthesis.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockParenthesis.java @@ -12,12 +12,12 @@ public class BlockParenthesis extends BlockParenthesisAbstract { super(); } - public BlockParenthesis(ObjectArrayList blocks) { + public BlockParenthesis(final ObjectArrayList blocks) { super(blocks); } @Override - public Feature toFeature(MathContext context) throws Error { + public Feature toFeature(final MathContext context) throws Error { final Function cont = getNumberContainer().toFunction(context); return new FeatureParenthesis(cont); } diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockParenthesisAbstract.java b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockParenthesisAbstract.java index da8b0821..db9537d9 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockParenthesisAbstract.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockParenthesisAbstract.java @@ -17,7 +17,7 @@ public abstract class BlockParenthesisAbstract extends Block { private int chw; private int chh; - protected BlockParenthesisAbstract(String prefix) { + protected BlockParenthesisAbstract(final String prefix) { containerNumber = new BlockContainer(false); this.prefix = prefix; @@ -30,19 +30,18 @@ public abstract class BlockParenthesisAbstract extends Block { recomputeDimensions(); } - public BlockParenthesisAbstract(ObjectArrayList blocks) { + public BlockParenthesisAbstract(final ObjectArrayList blocks) { containerNumber = new BlockContainer(false, blocks); prefix = null; recomputeDimensions(); } @Override - public void draw(GraphicEngine ge, Renderer r, int x, int y, Caret caret) { + public void draw(final GraphicEngine ge, final Renderer r, final int x, final int y, final Caret caret) { BlockContainer.getDefaultFont(small).use(ge); r.glColor(BlockContainer.getDefaultColor()); - if (prefix != null) { + if (prefix != null) r.glDrawStringLeft(x + 1, y + line - chh / 2, prefix); - } r.glDrawCharLeft(x + prw, y, '╭'); r.glDrawCharLeft(x + prw, y + height - chh, '╰'); if (small) { @@ -58,37 +57,34 @@ public abstract class BlockParenthesisAbstract extends Block { } @Override - public boolean putBlock(Caret caret, Block newBlock) { + public boolean putBlock(final Caret caret, final Block newBlock) { boolean added = false; added = added | containerNumber.putBlock(caret, newBlock); - if (added) { + if (added) recomputeDimensions(); - } return added; } @Override - public boolean delBlock(Caret caret) { + public boolean delBlock(final Caret caret) { boolean removed = false; removed = removed | containerNumber.delBlock(caret); - if (removed) { + if (removed) recomputeDimensions(); - } return removed; } @Override - public BlockReference getBlock(Caret caret) { + public BlockReference getBlock(final Caret caret) { return containerNumber.getBlock(caret); } @Override public void recomputeDimensions() { - if (prefix == null) { + if (prefix == null) prw = 0; - } else { + else prw = 1 + BlockContainer.getDefaultCharWidth(small) * prefix.length() + 2; - } chw = BlockContainer.getDefaultCharWidth(small); chh = BlockContainer.getDefaultCharHeight(small); width = prw + chw + containerNumber.getWidth() + chw + 3; @@ -97,7 +93,7 @@ public abstract class BlockParenthesisAbstract extends Block { } @Override - public void setSmall(boolean small) { + public void setSmall(final boolean small) { this.small = small; containerNumber.setSmall(small); recomputeDimensions(); diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockPower.java b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockPower.java index fc4a9218..1fe926bd 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockPower.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockPower.java @@ -19,34 +19,32 @@ public class BlockPower extends Block { } @Override - public void draw(GraphicEngine ge, Renderer r, int x, int y, Caret caret) { + public void draw(final GraphicEngine ge, final Renderer r, final int x, final int y, final Caret caret) { BlockContainer.getDefaultFont(true).use(ge); r.glColor(BlockContainer.getDefaultColor()); containerExponent.draw(ge, r, x, y, caret); } @Override - public boolean putBlock(Caret caret, Block newBlock) { + public boolean putBlock(final Caret caret, final Block newBlock) { boolean added = false; added = added | containerExponent.putBlock(caret, newBlock); - if (added) { + if (added) recomputeDimensions(); - } return added; } @Override - public boolean delBlock(Caret caret) { + public boolean delBlock(final Caret caret) { boolean removed = false; removed = removed | containerExponent.delBlock(caret); - if (removed) { + if (removed) recomputeDimensions(); - } return removed; } @Override - public BlockReference getBlock(Caret caret) { + public BlockReference getBlock(final Caret caret) { return containerExponent.getBlock(caret); } @@ -60,7 +58,7 @@ public class BlockPower extends Block { } @Override - public void setSmall(boolean small) { + public void setSmall(final boolean small) { this.small = small; containerExponent.setSmall(true); recomputeDimensions(); @@ -76,7 +74,7 @@ public class BlockPower extends Block { } @Override - public Feature toFeature(MathContext context) throws Error { + public Feature toFeature(final MathContext context) throws Error { final Function exp = getExponentContainer().toFunction(context); return new FeaturePowerChar(exp); } diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockPower2.java b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockPower2.java index e89eac3a..d6c3cbee 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockPower2.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockPower2.java @@ -18,41 +18,39 @@ public class BlockPower2 extends Block { containerExponent.addBlock(0, new BlockNumericChar('2')); recomputeDimensions(); } - + @Override public int getCaretDeltaPositionAfterCreation() { return 3; } @Override - public void draw(GraphicEngine ge, Renderer r, int x, int y, Caret caret) { + public void draw(final GraphicEngine ge, final Renderer r, final int x, final int y, final Caret caret) { BlockContainer.getDefaultFont(true).use(ge); r.glColor(BlockContainer.getDefaultColor()); containerExponent.draw(ge, r, x, y, caret); } @Override - public boolean putBlock(Caret caret, Block newBlock) { + public boolean putBlock(final Caret caret, final Block newBlock) { boolean added = false; added = added | containerExponent.putBlock(caret, newBlock); - if (added) { + if (added) recomputeDimensions(); - } return added; } @Override - public boolean delBlock(Caret caret) { + public boolean delBlock(final Caret caret) { boolean removed = false; removed = removed | containerExponent.delBlock(caret); - if (removed) { + if (removed) recomputeDimensions(); - } return removed; } @Override - public BlockReference getBlock(Caret caret) { + public BlockReference getBlock(final Caret caret) { return containerExponent.getBlock(caret); } @@ -66,7 +64,7 @@ public class BlockPower2 extends Block { } @Override - public void setSmall(boolean small) { + public void setSmall(final boolean small) { this.small = small; containerExponent.setSmall(true); recomputeDimensions(); @@ -82,7 +80,7 @@ public class BlockPower2 extends Block { } @Override - public Feature toFeature(MathContext context) throws Error { + public Feature toFeature(final MathContext context) throws Error { final Function exp = getExponentContainer().toFunction(context); return new FeaturePowerChar(exp); } diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockReference.java b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockReference.java index 3615f98b..71f20f26 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockReference.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockReference.java @@ -5,7 +5,7 @@ public class BlockReference { private final BlockContainer container; private final int blockPosition; - public BlockReference(T block, int blockPosition, BlockContainer container) { + public BlockReference(final T block, final int blockPosition, final BlockContainer container) { this.block = block; this.blockPosition = blockPosition; this.container = container; @@ -39,14 +39,13 @@ public class BlockReference { return isInsideBounds(this.blockPosition - 1); } - private BlockReference getBlockAtSafe(int i) { - if (isInsideBounds(i)) { + private BlockReference getBlockAtSafe(final int i) { + if (isInsideBounds(i)) return container.getBlockAt(i); - } return null; } - private boolean isInsideBounds(int i) { + private boolean isInsideBounds(final int i) { return i < container.getSize() && i >= 0; } diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockSine.java b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockSine.java index f403bc04..c4d32433 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockSine.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockSine.java @@ -12,7 +12,7 @@ public class BlockSine extends BlockParenthesisAbstract { } @Override - public Feature toFeature(MathContext context) throws Error { + public Feature toFeature(final MathContext context) throws Error { final Function cont = getNumberContainer().toFunction(context); return new FeatureSine(cont); } diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockSquareRoot.java b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockSquareRoot.java index 3628c8d8..e3a68176 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockSquareRoot.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockSquareRoot.java @@ -21,7 +21,7 @@ public class BlockSquareRoot extends Block { } @Override - public void draw(GraphicEngine ge, Renderer r, int x, int y, Caret caret) { + public void draw(final GraphicEngine ge, final Renderer r, final int x, final int y, final Caret caret) { BlockContainer.getDefaultFont(small).use(ge); r.glColor(BlockContainer.getDefaultColor()); r.glDrawLine(x, y + height - 10 + 1, x, y + height - 10 + 2); // / @@ -36,27 +36,25 @@ public class BlockSquareRoot extends Block { } @Override - public boolean putBlock(Caret caret, Block newBlock) { + public boolean putBlock(final Caret caret, final Block newBlock) { boolean added = false; added = added | containerNumber.putBlock(caret, newBlock); - if (added) { + if (added) recomputeDimensions(); - } return added; } @Override - public boolean delBlock(Caret caret) { + public boolean delBlock(final Caret caret) { boolean removed = false; removed = removed | containerNumber.delBlock(caret); - if (removed) { + if (removed) recomputeDimensions(); - } return removed; } @Override - public BlockReference getBlock(Caret caret) { + public BlockReference getBlock(final Caret caret) { return containerNumber.getBlock(caret); } @@ -70,12 +68,12 @@ public class BlockSquareRoot extends Block { line = 3 + l1; if (height < 9) { height = 9; - line += (9 - (3 + h1)); + line += 9 - (3 + h1); } } @Override - public void setSmall(boolean small) { + public void setSmall(final boolean small) { this.small = small; containerNumber.setSmall(small); recomputeDimensions(); @@ -91,7 +89,7 @@ public class BlockSquareRoot extends Block { } @Override - public Feature toFeature(MathContext context) throws Error { + public Feature toFeature(final MathContext context) throws Error { final Function contnt = getNumberContainer().toFunction(context); return new FeatureSquareRoot(contnt); } diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockUndefined.java b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockUndefined.java index f4294db7..958e29a2 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockUndefined.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockUndefined.java @@ -15,24 +15,24 @@ public class BlockUndefined extends Block { } @Override - public void draw(GraphicEngine ge, Renderer r, int x, int y, Caret caret) { + public void draw(final GraphicEngine ge, final Renderer r, final int x, final int y, final Caret caret) { BlockContainer.getDefaultFont(small).use(ge); r.glColor(BlockContainer.getDefaultColor()); r.glDrawStringLeft(x, y, "UNDEFINED"); } @Override - public boolean putBlock(Caret caret, Block newBlock) { + public boolean putBlock(final Caret caret, final Block newBlock) { return false; } @Override - public boolean delBlock(Caret caret) { + public boolean delBlock(final Caret caret) { return false; } @Override - public BlockReference getBlock(Caret caret) { + public BlockReference getBlock(final Caret caret) { return null; } @@ -44,7 +44,7 @@ public class BlockUndefined extends Block { } @Override - public void setSmall(boolean small) { + public void setSmall(final boolean small) { this.small = small; recomputeDimensions(); } @@ -55,7 +55,7 @@ public class BlockUndefined extends Block { } @Override - public Feature toFeature(MathContext context) { + public Feature toFeature(final MathContext context) { return new FeatureChar(MathematicalSymbols.UNDEFINED); } diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockVariable.java b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockVariable.java index 2ff29b00..e7aa8c87 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockVariable.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/blocks/BlockVariable.java @@ -26,11 +26,11 @@ public class BlockVariable extends Block { private BlockVariable typeDirtyID; private final boolean typeLocked; - public BlockVariable(InputContext ic, char ch) { + public BlockVariable(final InputContext ic, final char ch) { this(ic, ch, false); } - public BlockVariable(InputContext ic, char ch, boolean typeLocked) { + public BlockVariable(final InputContext ic, final char ch, final boolean typeLocked) { this.ic = ic; this.ch = ch; type = V_TYPE.VARIABLE; @@ -44,13 +44,11 @@ public class BlockVariable extends Block { private void retrieveValue() { type = ic.variableTypes.get(ch); - if (type == null) { + if (type == null) type = V_TYPE.VARIABLE; - } typeDirtyID = ic.variableTypeDirtyID; - if (menu != null) { + if (menu != null) menu.mustRefreshMenu = true; - } mustRefresh = true; System.out.println("retrieve:" + type.toString()); } @@ -68,10 +66,9 @@ public class BlockVariable extends Block { } @Override - public void draw(GraphicEngine ge, Renderer r, int x, int y, Caret caret) { - if (ic.variableTypeDirtyID != typeDirtyID) { + public void draw(final GraphicEngine ge, final Renderer r, final int x, final int y, final Caret caret) { + if (ic.variableTypeDirtyID != typeDirtyID) retrieveValue(); - } if (mustRefresh) { mustRefresh = false; switch (type) { @@ -94,17 +91,17 @@ public class BlockVariable extends Block { } @Override - public boolean putBlock(Caret caret, Block newBlock) { + public boolean putBlock(final Caret caret, final Block newBlock) { return false; } @Override - public boolean delBlock(Caret caret) { + public boolean delBlock(final Caret caret) { return false; } @Override - public BlockReference getBlock(Caret caret) { + public BlockReference getBlock(final Caret caret) { return null; } @@ -116,7 +113,7 @@ public class BlockVariable extends Block { } @Override - public void setSmall(boolean small) { + public void setSmall(final boolean small) { this.small = small; recomputeDimensions(); } @@ -140,7 +137,7 @@ public class BlockVariable extends Block { String text = ""; boolean mustRefreshMenu = true; - public VariableMenu(BlockVariable var) { + public VariableMenu(final BlockVariable var) { super(var); } @@ -155,7 +152,7 @@ public class BlockVariable extends Block { public void close() {} @Override - public boolean onKeyPressed(KeyPressedEvent k) { + public boolean onKeyPressed(final KeyPressedEvent k) { switch (k.getKey()) { case LEFT: case UP: @@ -200,12 +197,12 @@ public class BlockVariable extends Block { } @Override - public boolean onKeyReleased(KeyReleasedEvent k) { + public boolean onKeyReleased(final KeyReleasedEvent k) { return false; } @Override - public boolean beforeRender(float delta, Caret caret) { + public boolean beforeRender(final float delta, final Caret caret) { if (mustRefreshMenu) { mustRefreshMenu = false; text = block.type.toString(); @@ -220,24 +217,20 @@ public class BlockVariable extends Block { } @Override - public void draw(GraphicEngine ge, Renderer r, Caret caret) { + public void draw(final GraphicEngine ge, final Renderer r, final Caret caret) { r.glColor3f(1.0f, 1.0f, 1.0f); Engine.INSTANCE.getHardwareDevice().getDisplayManager().guiSkin.use(ge); int popupX = location[0]; int popupY = location[1]; - if (popupX < 0) { + if (popupX < 0) popupX = 0; - } - if (popupY < 0) { + if (popupY < 0) popupY = 0; - } final int[] screenSize = ge.getSize(); - if (popupX + width >= screenSize[0]) { + if (popupX + width >= screenSize[0]) popupX = screenSize[0] - width - 1; - } - if (popupY + height >= screenSize[1]) { + if (popupY + height >= screenSize[1]) popupY = screenSize[1] - height - 1; - } r.glFillRect(location[0] + width / 2 - 5, popupY + 1, 10, 5, 163, 16, 10, 5); r.glFillColor(popupX, popupY + 5, width, height); r.glFillColor(popupX + 2, popupY + 4, width - 4, height + 2); @@ -252,7 +245,7 @@ public class BlockVariable extends Block { } @Override - public Feature toFeature(MathContext context) throws Error { + public Feature toFeature(final MathContext context) throws Error { return new FeatureVariable(ch, type); } } diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/containers/InlineInputContainer.java b/core/src/main/java/it/cavallium/warppi/gui/expression/containers/InlineInputContainer.java index f42091b3..20c85d42 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/containers/InlineInputContainer.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/containers/InlineInputContainer.java @@ -16,20 +16,20 @@ public class InlineInputContainer extends InputContainer { super(); } - public InlineInputContainer(InputContext ic) { + public InlineInputContainer(final InputContext ic) { super(ic); } - public InlineInputContainer(InputContext ic, boolean small) { + public InlineInputContainer(final InputContext ic, final boolean small) { super(ic, small); } - public InlineInputContainer(InputContext ic, boolean small, int minWidth, int minHeight) { + public InlineInputContainer(final InputContext ic, final boolean small, final int minWidth, final int minHeight) { super(ic, small, minWidth, minHeight); } @Override - public Block parseChar(char c) { + public Block parseChar(final char c) { return new BlockChar(c); } } diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/containers/InputContainer.java b/core/src/main/java/it/cavallium/warppi/gui/expression/containers/InputContainer.java index 67c768fd..b8e0cf5d 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/containers/InputContainer.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/containers/InputContainer.java @@ -42,26 +42,26 @@ public abstract class InputContainer implements GraphicalElement, InputLayout, S this(new InputContext()); } - public InputContainer(InputContext ic) { + public InputContainer(final InputContext ic) { this(ic, false); } - public InputContainer(InputContext ic, boolean small) { + public InputContainer(final InputContext ic, final boolean small) { this(ic, small, 0, 0); } - public InputContainer(InputContext ic, boolean small, int minWidth, int minHeight) { + public InputContainer(final InputContext ic, final boolean small, final int minWidth, final int minHeight) { inputContext = ic; caret = new Caret(CaretState.VISIBLE_ON, 0); root = new BlockContainer(small, false); } - public void typeChar(char c) { + public void typeChar(final char c) { final Block b = parseChar(c); typeBlock(b); } - public void typeBlock(Block b) { + public void typeBlock(final Block b) { if (b != null) { caret.resetRemaining(); if (root.putBlock(caret, b)) { @@ -75,15 +75,14 @@ public abstract class InputContainer implements GraphicalElement, InputLayout, S closeExtra(); } - public void typeChar(String c) { + public void typeChar(final String c) { typeChar(c.charAt(0)); } public void del() { caret.resetRemaining(); - if (root.delBlock(caret)) { + if (root.delBlock(caret)) root.recomputeDimensions(); - } if (caret.getPosition() > 0) { caret.setPosition(caret.getPosition() - 1); maxPosition = root.computeCaretMaxBound(); @@ -101,11 +100,10 @@ public abstract class InputContainer implements GraphicalElement, InputLayout, S public void moveLeft() { final int curPos = caret.getPosition(); - if (curPos > 0) { + if (curPos > 0) caret.setPosition(curPos - 1); - } else { + else caret.setPosition(maxPosition - 1); - } caret.turnOn(); caretTime = 0; closeExtra(); @@ -113,11 +111,10 @@ public abstract class InputContainer implements GraphicalElement, InputLayout, S public void moveRight() { final int curPos = caret.getPosition(); - if (curPos + 1 < maxPosition) { + if (curPos + 1 < maxPosition) caret.setPosition(curPos + 1); - } else { + else caret.setPosition(0); - } caret.turnOn(); caretTime = 0; closeExtra(); @@ -144,31 +141,29 @@ public abstract class InputContainer implements GraphicalElement, InputLayout, S } /** - * + * * @param delta * Time, in seconds * @return true if something changed */ - public boolean beforeRender(float delta) { + public boolean beforeRender(final float delta) { boolean somethingChanged = false; caretTime += delta; - if (caretTime >= CARET_DURATION) { - while (caretTime >= CARET_DURATION) { - caretTime -= CARET_DURATION; + if (caretTime >= InputContainer.CARET_DURATION) + while (caretTime >= InputContainer.CARET_DURATION) { + caretTime -= InputContainer.CARET_DURATION; caret.flipState(); somethingChanged = true; } - } - if (extra != null) { + if (extra != null) somethingChanged = somethingChanged | extra.beforeRender(delta, caret); - } return somethingChanged; } /** - * + * * @param ge * Graphic Engine class. * @param r @@ -178,12 +173,11 @@ public abstract class InputContainer implements GraphicalElement, InputLayout, S * @param y * Position relative to the window. */ - public void draw(GraphicEngine ge, Renderer r, int x, int y) { + public void draw(final GraphicEngine ge, final Renderer r, final int x, final int y) { caret.resetRemaining(); root.draw(ge, r, x, y, caret); - if (extra != null) { + if (extra != null) extra.draw(ge, r, caret); - } } public void clear() { @@ -201,16 +195,15 @@ public abstract class InputContainer implements GraphicalElement, InputLayout, S return maxPosition; } - public void setCaretPosition(int pos) { - if (pos > 0 && pos < maxPosition) { + public void setCaretPosition(final int pos) { + if (pos > 0 && pos < maxPosition) caret.setPosition(pos); - } caret.turnOn(); caretTime = 0; closeExtra(); } - public void setParsed(boolean parsed) { + public void setParsed(final boolean parsed) { this.parsed = parsed; } @@ -220,7 +213,7 @@ public abstract class InputContainer implements GraphicalElement, InputLayout, S /** * WARNING! DO NOT MODIFY THIS ARRAY!!! - * + * * @return an arraylist representing the content */ public ObjectArrayList getContent() { @@ -232,9 +225,8 @@ public abstract class InputContainer implements GraphicalElement, InputLayout, S final BlockReference selectedBlock = getSelectedBlock(); if (selectedBlock != null) { extra = selectedBlock.get().getExtraMenu(); - if (extra != null) { + if (extra != null) extra.open(); - } } } else { extra.close(); @@ -257,7 +249,7 @@ public abstract class InputContainer implements GraphicalElement, InputLayout, S return extra; } - public Function toFunction(MathContext context) throws Error { + public Function toFunction(final MathContext context) throws Error { return root.toFunction(context); } diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/containers/NormalInputContainer.java b/core/src/main/java/it/cavallium/warppi/gui/expression/containers/NormalInputContainer.java index b7620e4b..6a05f41b 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/containers/NormalInputContainer.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/containers/NormalInputContainer.java @@ -28,20 +28,20 @@ public class NormalInputContainer extends InputContainer { super(); } - public NormalInputContainer(InputContext ic) { + public NormalInputContainer(final InputContext ic) { super(ic); } - public NormalInputContainer(InputContext ic, boolean small) { + public NormalInputContainer(final InputContext ic, final boolean small) { super(ic, small); } - public NormalInputContainer(InputContext ic, boolean small, int minWidth, int minHeight) { + public NormalInputContainer(final InputContext ic, final boolean small, final int minWidth, final int minHeight) { super(ic, small, minWidth, minHeight); } @Override - public Block parseChar(char c) { + public Block parseChar(final char c) { switch (c) { case MathematicalSymbols.DIVISION: return new BlockDivision(); @@ -81,17 +81,15 @@ public class NormalInputContainer extends InputContainer { case MathematicalSymbols.EULER_NUMBER: return new BlockVariable(inputContext, c, true); default: - for (final char v : MathematicalSymbols.variables) { - if (c == v) { + for (final char v : MathematicalSymbols.variables) + if (c == v) return new BlockVariable(inputContext, c); - } - } return new BlockChar(c); } } @Override - public void typeChar(char c) { + public void typeChar(final char c) { super.typeChar(c); switch (c) { case MathematicalSymbols.PARENTHESIS_CLOSE: @@ -106,18 +104,15 @@ public class NormalInputContainer extends InputContainer { int before = 0; while (true) { currentBlock = currentBlock.getPreviousBlock(); - if (currentBlock == null) { + if (currentBlock == null) break; - } final Block b = currentBlock.get(); if (b instanceof BlockNumericChar || b instanceof BlockVariable) { - if (!groupedBefore) { + if (!groupedBefore) groupedBefore = true; - } before++; - } else { + } else break; - } } if (groupedBefore) { moveLeft(); @@ -129,9 +124,8 @@ public class NormalInputContainer extends InputContainer { moveLeft(); moveLeft(); } - for (int i = 0; i < before + 1; i++) { + for (int i = 0; i < before + 1; i++) moveRight(); - } moveRight();// Move to the divisor } diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/containers/NormalOutputContainer.java b/core/src/main/java/it/cavallium/warppi/gui/expression/containers/NormalOutputContainer.java index 929cedaf..a5c6a632 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/containers/NormalOutputContainer.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/containers/NormalOutputContainer.java @@ -8,11 +8,11 @@ public class NormalOutputContainer extends OutputContainer { super(); } - public NormalOutputContainer(boolean small) { + public NormalOutputContainer(final boolean small) { super(small); } - public NormalOutputContainer(boolean small, int minWidth, int minHeight) { + public NormalOutputContainer(final boolean small, final int minWidth, final int minHeight) { super(small, minWidth, minHeight); } } diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/containers/OutputContainer.java b/core/src/main/java/it/cavallium/warppi/gui/expression/containers/OutputContainer.java index b68c5590..16fef8d0 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/containers/OutputContainer.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/containers/OutputContainer.java @@ -22,39 +22,37 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout, roots.add(new BlockContainer()); } - public OutputContainer(boolean small) { + public OutputContainer(final boolean small) { roots = new ObjectArrayList<>(); roots.add(new BlockContainer(small)); } - public OutputContainer(boolean small, int minWidth, int minHeight) { + public OutputContainer(final boolean small, final int minWidth, final int minHeight) { roots = new ObjectArrayList<>(); roots.add(new BlockContainer(small)); } - public void setContentAsSingleGroup(ObjectArrayList blocks) { + public void setContentAsSingleGroup(final ObjectArrayList blocks) { roots.clear(); final BlockContainer bcnt = new BlockContainer(); - for (final Block block : blocks) { + for (final Block block : blocks) bcnt.appendBlockUnsafe(block); - } roots.add(bcnt); recomputeDimensions(); } - public void setContentAsMultipleGroups(ObjectArrayList> roots) { + public void setContentAsMultipleGroups(final ObjectArrayList> roots) { this.roots.clear(); for (final ObjectArrayList blocks : roots) { final BlockContainer bcnt = new BlockContainer(); - for (final Block block : blocks) { + for (final Block block : blocks) bcnt.appendBlockUnsafe(block); - } this.roots.add(bcnt); } recomputeDimensions(); } - public void setContentAsMultipleElements(ObjectArrayList elems) { + public void setContentAsMultipleElements(final ObjectArrayList elems) { roots.clear(); for (final Block block : elems) { final BlockContainer bcnt = new BlockContainer(); @@ -66,9 +64,8 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout, @Override public void recomputeDimensions() { - for (final BlockContainer root : roots) { + for (final BlockContainer root : roots) root.recomputeDimensions(); - } } @Override @@ -76,9 +73,8 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout, int maxw = 0; for (final BlockContainer root : roots) { final int w = root.getWidth(); - if (w > maxw) { + if (w > maxw) maxw = w; - } } return maxw; } @@ -86,14 +82,12 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout, @Override public int getHeight() { int h = 0; - for (final BlockContainer root : roots) { + for (final BlockContainer root : roots) h += root.getHeight() + 2; - } - if (h > 0) { + if (h > 0) return h - 2; - } else { + else return h; - } } @Override @@ -102,16 +96,16 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout, } /** - * + * * @param delta * Time, in seconds */ - public void beforeRender(double delta) { + public void beforeRender(final double delta) { } /** - * + * * @param ge * Graphic Engine class. * @param r @@ -121,7 +115,7 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout, * @param y * Position relative to the window. */ - public void draw(GraphicEngine ge, Renderer r, int x, int y) { + public void draw(final GraphicEngine ge, final Renderer r, final int x, final int y) { int offset = 0; for (final BlockContainer root : roots) { root.draw(ge, r, x, y + offset, caret); @@ -138,9 +132,8 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout, public boolean isContentEmpty() { for (final BlockContainer root : roots) { final ObjectArrayList cnt = root.getContent(); - if (cnt != null && !cnt.isEmpty()) { + if (cnt != null && !cnt.isEmpty()) return false; - } } return true; } diff --git a/core/src/main/java/it/cavallium/warppi/gui/expression/layouts/InputLayout.java b/core/src/main/java/it/cavallium/warppi/gui/expression/layouts/InputLayout.java index 88a970db..f4008b4f 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/expression/layouts/InputLayout.java +++ b/core/src/main/java/it/cavallium/warppi/gui/expression/layouts/InputLayout.java @@ -3,5 +3,5 @@ package it.cavallium.warppi.gui.expression.layouts; import it.cavallium.warppi.gui.expression.blocks.Block; public interface InputLayout { - public Block parseChar(char c); + Block parseChar(char c); } diff --git a/core/src/main/java/it/cavallium/warppi/gui/graphicengine/BinaryFont.java b/core/src/main/java/it/cavallium/warppi/gui/graphicengine/BinaryFont.java index ca4318e4..64116cf4 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/graphicengine/BinaryFont.java +++ b/core/src/main/java/it/cavallium/warppi/gui/graphicengine/BinaryFont.java @@ -6,9 +6,9 @@ package it.cavallium.warppi.gui.graphicengine; */ public interface BinaryFont extends Skin { - public int getStringWidth(String text); + int getStringWidth(String text); - public int getCharacterWidth(); + int getCharacterWidth(); - public int getCharacterHeight(); + int getCharacterHeight(); } diff --git a/core/src/main/java/it/cavallium/warppi/gui/graphicengine/GraphicEngine.java b/core/src/main/java/it/cavallium/warppi/gui/graphicengine/GraphicEngine.java index 88d4f1cc..6ff150b0 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/graphicengine/GraphicEngine.java +++ b/core/src/main/java/it/cavallium/warppi/gui/graphicengine/GraphicEngine.java @@ -7,53 +7,53 @@ import it.cavallium.warppi.flow.Observable; public interface GraphicEngine { - public int[] getSize(); + int[] getSize(); - public boolean isInitialized(); + boolean isInitialized(); - public void setTitle(String title); + void setTitle(String title); - public void setResizable(boolean r); + void setResizable(boolean r); - public void setDisplayMode(final int ww, final int wh); + void setDisplayMode(final int ww, final int wh); - public default void create() { + default void create() { create(null); }; - public void create(Runnable object); + void create(Runnable object); - public Observable onResize(); + Observable onResize(); - public int getWidth(); + int getWidth(); - public int getHeight(); + int getHeight(); - public void destroy(); + void destroy(); - public void start(RenderingLoop d); + void start(RenderingLoop d); - public void repaint(); + void repaint(); - public Renderer getRenderer(); + Renderer getRenderer(); - public BinaryFont loadFont(String fontName) throws IOException; + BinaryFont loadFont(String fontName) throws IOException; - public BinaryFont loadFont(String path, String fontName) throws IOException; + BinaryFont loadFont(String path, String fontName) throws IOException; - public Skin loadSkin(String file) throws IOException; + Skin loadSkin(String file) throws IOException; - public void waitForExit(); + void waitForExit(); - public boolean isSupported(); + boolean isSupported(); - public boolean doesRefreshPauses(); + boolean doesRefreshPauses(); - public default boolean supportsFontRegistering() { + default boolean supportsFontRegistering() { return false; } - public default List getRegisteredFonts() { + default List getRegisteredFonts() { return null; } } diff --git a/core/src/main/java/it/cavallium/warppi/gui/graphicengine/Renderer.java b/core/src/main/java/it/cavallium/warppi/gui/graphicengine/Renderer.java index 5a367a07..25dba65c 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/graphicengine/Renderer.java +++ b/core/src/main/java/it/cavallium/warppi/gui/graphicengine/Renderer.java @@ -1,46 +1,45 @@ package it.cavallium.warppi.gui.graphicengine; public interface Renderer { - public void glColor3i(int r, int gg, int b); + void glColor3i(int r, int gg, int b); - public void glColor(int c); + void glColor(int c); - public void glColor4i(int red, int green, int blue, int alpha); + void glColor4i(int red, int green, int blue, int alpha); - public void glColor3f(float red, float green, float blue); + void glColor3f(float red, float green, float blue); - public void glColor4f(float red, float green, float blue, float alpha); + void glColor4f(float red, float green, float blue, float alpha); - public void glClearColor4i(int red, int green, int blue, int alpha); + void glClearColor4i(int red, int green, int blue, int alpha); - public void glClearColor4f(float red, float green, float blue, float alpha); + void glClearColor4f(float red, float green, float blue, float alpha); - public int glGetClearColor(); + int glGetClearColor(); - public void glClearColor(int c); + void glClearColor(int c); - public void glClear(int screenWidth, int screenHeight); + void glClear(int screenWidth, int screenHeight); - public void glDrawLine(float x0, float y0, float x1, float y1); + void glDrawLine(float x0, float y0, float x1, float y1); - public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth, - float uvHeight); + void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth, float uvHeight); - public void glFillColor(float x, float y, float width, float height); + void glFillColor(float x, float y, float width, float height); - public void glDrawCharLeft(int x, int y, char ch); + void glDrawCharLeft(int x, int y, char ch); - public void glDrawCharCenter(int x, int y, char ch); + void glDrawCharCenter(int x, int y, char ch); - public void glDrawCharRight(int x, int y, char ch); + void glDrawCharRight(int x, int y, char ch); - public void glDrawStringLeft(float x, float y, String text); + void glDrawStringLeft(float x, float y, String text); - public void glDrawStringCenter(float x, float y, String text); + void glDrawStringCenter(float x, float y, String text); - public void glDrawStringRight(float x, float y, String text); + void glDrawStringRight(float x, float y, String text); - public void glClearSkin(); + void glClearSkin(); - public BinaryFont getCurrentFont(); + BinaryFont getCurrentFont(); } \ No newline at end of file diff --git a/core/src/main/java/it/cavallium/warppi/gui/graphicengine/RenderingLoop.java b/core/src/main/java/it/cavallium/warppi/gui/graphicengine/RenderingLoop.java index 24307987..7960f81e 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/graphicengine/RenderingLoop.java +++ b/core/src/main/java/it/cavallium/warppi/gui/graphicengine/RenderingLoop.java @@ -1,5 +1,5 @@ package it.cavallium.warppi.gui.graphicengine; public interface RenderingLoop { - public void refresh(); + void refresh(); } diff --git a/core/src/main/java/it/cavallium/warppi/gui/graphicengine/Skin.java b/core/src/main/java/it/cavallium/warppi/gui/graphicengine/Skin.java index bdf38fb8..5469dbdd 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/graphicengine/Skin.java +++ b/core/src/main/java/it/cavallium/warppi/gui/graphicengine/Skin.java @@ -5,15 +5,15 @@ import java.net.URISyntaxException; public interface Skin { - public void load(String file) throws IOException, URISyntaxException; + void load(String file) throws IOException, URISyntaxException; - public void initialize(GraphicEngine d); + void initialize(GraphicEngine d); - public boolean isInitialized(); + boolean isInitialized(); - public void use(GraphicEngine d); + void use(GraphicEngine d); - public int getSkinWidth(); + int getSkinWidth(); - public int getSkinHeight(); + int getSkinHeight(); } diff --git a/core/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/common/PngSkin.java b/core/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/common/PngSkin.java index c6d010ff..726f209e 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/common/PngSkin.java +++ b/core/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/common/PngSkin.java @@ -19,25 +19,24 @@ public abstract class PngSkin implements Skin { @SuppressWarnings("unused") private final boolean isResource; - public PngSkin(String file) throws IOException { + public PngSkin(final String file) throws IOException { isResource = !new File(file).exists(); load(file); } - @SuppressWarnings("unused") @Override public void load(String file) throws IOException { if (!file.startsWith("/")) file = "/" + file; try { if (!file.endsWith(".png")) { - File f = File.createTempFile("picalculator-png", ".png"); + final File f = File.createTempFile("picalculator-png", ".png"); f.deleteOnExit(); - BufferedImage img = ImageIO.read(Engine.getPlatform().getStorageUtils().getResourceStream(file)); + final BufferedImage img = ImageIO.read(Engine.getPlatform().getStorageUtils().getResourceStream(file)); ImageIO.write(img, "PNG", f); file = f.toString(); } - PngReader r = Engine.getPlatform().getPngUtils().load(Engine.getPlatform().getStorageUtils().getResourceStream(file)); + final PngReader r = Engine.getPlatform().getPngUtils().load(Engine.getPlatform().getStorageUtils().getResourceStream(file)); if (r == null) { skinData = new int[0]; skinSize = new int[] { 0, 0 }; @@ -46,15 +45,15 @@ public abstract class PngSkin implements Skin { skinData = r.getImageMatrix(); skinSize = r.getSize(); } - } catch (URISyntaxException e) { - IOException ex = new IOException(); + } catch (final URISyntaxException e) { + final IOException ex = new IOException(); ex.initCause(e); throw ex; } } @Override - public void initialize(GraphicEngine d) { + public void initialize(final GraphicEngine d) { // TODO Auto-generated method stub } diff --git a/core/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/common/RFTFont.java b/core/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/common/RFTFont.java index 745aff57..f95335d8 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/common/RFTFont.java +++ b/core/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/common/RFTFont.java @@ -34,49 +34,49 @@ public abstract class RFTFont implements BinaryFont { @SuppressWarnings("unused") private final boolean isResource; - public RFTFont(String fontName) throws IOException { + public RFTFont(final String fontName) throws IOException { this(fontName, false); } - RFTFont(String fontName, boolean onlyRaw) throws IOException { + RFTFont(final String fontName, final boolean onlyRaw) throws IOException { isResource = true; load("/font_" + fontName + ".rft", onlyRaw); } - public RFTFont(String path, String fontName) throws IOException { + public RFTFont(final String path, final String fontName) throws IOException { this(path, fontName, false); } - RFTFont(String path, String fontName, boolean onlyRaw) throws IOException { + RFTFont(final String path, final String fontName, final boolean onlyRaw) throws IOException { isResource = false; load(path + "/font_" + fontName + ".rft", onlyRaw); } - public static RFTFont loadTemporaryFont(String name) throws IOException { + public static RFTFont loadTemporaryFont(final String name) throws IOException { return new BlankRFTFont(name, true); } - public static RFTFont loadTemporaryFont(String path, String name) throws IOException { + public static RFTFont loadTemporaryFont(final String path, final String name) throws IOException { return new BlankRFTFont(path, name, true); } @Override - public void load(String path) throws IOException { + public void load(final String path) throws IOException { load(path, false); } - private void load(String path, boolean onlyRaw) throws IOException { + private void load(final String path, final boolean onlyRaw) throws IOException { Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_MIN + 1, "Loading font " + path); loadFont(path); if (!onlyRaw) { - chars32 = new int[(intervalsTotalSize) * charIntCount]; + chars32 = new int[intervalsTotalSize * charIntCount]; for (int charCompressedIndex = 0; charCompressedIndex < intervalsTotalSize; charCompressedIndex++) { final boolean[] currentChar = rawchars[charCompressedIndex]; if (currentChar == null) { int currentInt = 0; int currentBit = 0; for (int i = 0; i < charS; i++) { - if (currentInt * intBits + currentBit >= (currentInt + 1) * intBits) { + if (currentInt * RFTFont.intBits + currentBit >= (currentInt + 1) * RFTFont.intBits) { currentInt += 1; currentBit = 0; } @@ -87,11 +87,11 @@ public abstract class RFTFont implements BinaryFont { int currentInt = 0; int currentBit = 0; for (int i = 0; i < charS; i++) { - if (currentBit >= intBits) { + if (currentBit >= RFTFont.intBits) { currentInt += 1; currentBit = 0; } - chars32[charCompressedIndex * charIntCount + currentInt] = (chars32[charCompressedIndex * charIntCount + currentInt]) | ((currentChar[i] ? 1 : 0) << currentBit); + chars32[charCompressedIndex * charIntCount + currentInt] = chars32[charCompressedIndex * charIntCount + currentInt] | (currentChar[i] ? 1 : 0) << currentBit; currentBit++; } } @@ -107,8 +107,8 @@ public abstract class RFTFont implements BinaryFont { if (!string.startsWith("/")) string = "/" + string; res = Engine.getPlatform().getStorageUtils().getResourceStream(string); - } catch (URISyntaxException e) { - IOException ex = new IOException(); + } catch (final URISyntaxException e) { + final IOException ex = new IOException(); ex.initCause(e); throw ex; } @@ -119,32 +119,28 @@ public abstract class RFTFont implements BinaryFont { charW = file[0x4] << 8 | file[0x5]; charH = file[0x6] << 8 | file[0x7]; charS = charW * charH; - charIntCount = (int) Math.ceil(((double) charS) / ((double) intBits)); + charIntCount = (int) Math.ceil((double) charS / (double) RFTFont.intBits); minBound = file[0x9] << 24 | file[0xA] << 16 | file[0xB] << 8 | file[0xC]; maxBound = file[0xE] << 24 | file[0xF] << 16 | file[0x10] << 8 | file[0x11]; - if (maxBound <= minBound) { + if (maxBound <= minBound) maxBound = 66000; //TODO remove it: temp fix - } rawchars = new boolean[maxBound - minBound][]; int index = 0x12; - while (index < filelength) { + while (index < filelength) try { final int charIndex = file[index] << 8 | file[index + 1]; final boolean[] rawchar = new boolean[charS]; int charbytescount = 0; - while (charbytescount * 8 < charS) { + while (charbytescount * 8 < charS) charbytescount += 1; - } int currentBit = 0; - for (int i = 0; i <= charbytescount; i++) { + for (int i = 0; i <= charbytescount; i++) for (int bit = 0; bit < 8; bit++) { - if (currentBit >= charS) { + if (currentBit >= charS) break; - } - rawchar[currentBit] = (((file[index + 2 + i] >> (8 - 1 - bit)) & 0x1) == 1) ? true : false; + rawchar[currentBit] = (file[index + 2 + i] >> 8 - 1 - bit & 0x1) == 1 ? true : false; currentBit++; } - } rawchars[charIndex - minBound] = rawchar; index += 2 + charbytescount; } catch (final Exception ex) { @@ -152,13 +148,10 @@ public abstract class RFTFont implements BinaryFont { System.out.println(string); Engine.getPlatform().exit(-1); } - } - } else { + } else throw new IOException(); - } - } else { + } else throw new IOException(); - } findIntervals(); /*int[] screen = new int[rawchars.length * charW * charH]; for (int i = 0; i < rawchars.length; i++) { @@ -186,13 +179,12 @@ public abstract class RFTFont implements BinaryFont { int intervalSize = 0; @SuppressWarnings("unused") final int holeSize = 0; - for (int i = 0; i < rawchars.length; i++) { + for (int i = 0; i < rawchars.length; i++) if (rawchars[i] != null) { beginIndex = i; int firstNull = 0; - while (i + firstNull < rawchars.length && rawchars[i + firstNull] != null) { + while (i + firstNull < rawchars.length && rawchars[i + firstNull] != null) firstNull++; - } endIndex = beginIndex + firstNull - 1; i = endIndex; if (endIndex >= 0) { @@ -202,13 +194,12 @@ public abstract class RFTFont implements BinaryFont { } beginIndex = -1; } - } int lastIndex = 0; final boolean[][] newrawchars = new boolean[intervalsTotalSize][]; for (final int[] interval : intervals) { - if (rawchars.length - (interval[0]) - interval[2] < 0) { + if (rawchars.length - interval[0] - interval[2] < 0) { System.err.println(interval[0] + "-" + interval[1] + "(" + interval[2] + ")"); - System.err.println(rawchars.length - (interval[0]) - interval[2]); + System.err.println(rawchars.length - interval[0] - interval[2]); throw new ArrayIndexOutOfBoundsException(); } if (newrawchars.length - (lastIndex - 1) - interval[2] < 0) { @@ -230,7 +221,7 @@ public abstract class RFTFont implements BinaryFont { } @SuppressWarnings("unused") - private void saveArray(int[] screen, int w, int h, String coutputpng) { + private void saveArray(final int[] screen, final int w, final int h, final String coutputpng) { final BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); final int[] a = ((DataBufferInt) bi.getRaster().getDataBuffer()).getData(); System.arraycopy(screen, 0, a, 0, screen.length); @@ -241,7 +232,7 @@ public abstract class RFTFont implements BinaryFont { } } - public int[] getCharIndexes(String txt) { + public int[] getCharIndexes(final String txt) { final int l = txt.length(); final int[] indexes = new int[l]; final char[] chars = txt.toCharArray(); @@ -252,52 +243,48 @@ public abstract class RFTFont implements BinaryFont { return indexes; } - public int getCharIndex(char c) { + public int getCharIndex(final char c) { final int originalIndex = c & 0xFFFF; return compressIndex(originalIndex); } - protected int compressIndex(int originalIndex) { + protected int compressIndex(final int originalIndex) { int compressedIndex = 0; - for (int i = 0; i < intervals.length; i += 3) { - if (intervals[i] > originalIndex) { + for (int i = 0; i < intervals.length; i += 3) + if (intervals[i] > originalIndex) break; - } else if (originalIndex <= intervals[i + 1]) { - compressedIndex += (originalIndex - intervals[i]); + else if (originalIndex <= intervals[i + 1]) { + compressedIndex += originalIndex - intervals[i]; break; - } else { + } else compressedIndex += intervals[i + 2]; - } - } return compressedIndex; } @SuppressWarnings("unused") - private int decompressIndex(int compressedIndex) { + private int decompressIndex(final int compressedIndex) { final int originalIndex = 0; int i = 0; for (int intvl = 0; intvl < intervals.length; intvl += 3) { i += intervals[intvl + 2]; - if (i == compressedIndex) { + if (i == compressedIndex) return intervals[intvl + 1]; - } else if (i > compressedIndex) { + else if (i > compressedIndex) return intervals[intvl + 1] - (i - compressedIndex); - } } return originalIndex; } @Override - public void initialize(GraphicEngine d) {} + public void initialize(final GraphicEngine d) {} @Override - public int getStringWidth(String text) { + public int getStringWidth(final String text) { final int w = charW * text.length(); - if (text.length() > 0 && w > 0) { + if (text.length() > 0 && w > 0) return w; - } else { + else return 0; - } } @Override @@ -324,22 +311,22 @@ public abstract class RFTFont implements BinaryFont { public int getSkinHeight() { return -1; } - + private static class BlankRFTFont extends RFTFont { - BlankRFTFont(String fontName, boolean onlyRaw) throws IOException { + BlankRFTFont(final String fontName, final boolean onlyRaw) throws IOException { super(fontName, onlyRaw); } - public BlankRFTFont(String path, String name, boolean b) throws IOException { + public BlankRFTFont(final String path, final String name, final boolean b) throws IOException { super(path, name, b); } @Override - public void use(GraphicEngine d) { - + public void use(final GraphicEngine d) { + } - + } } diff --git a/core/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/nogui/NoGuiEngine.java b/core/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/nogui/NoGuiEngine.java index 9eab880b..ad784593 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/nogui/NoGuiEngine.java +++ b/core/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/nogui/NoGuiEngine.java @@ -27,20 +27,19 @@ public class NoGuiEngine implements GraphicEngine { } @Override - public void setTitle(String title) {} + public void setTitle(final String title) {} @Override - public void setResizable(boolean r) {} + public void setResizable(final boolean r) {} @Override - public void setDisplayMode(int ww, int wh) {} + public void setDisplayMode(final int ww, final int wh) {} @Override - public void create(Runnable onInitialized) { + public void create(final Runnable onInitialized) { initialized = true; - if (onInitialized != null) { + if (onInitialized != null) onInitialized.run(); - } } @Override @@ -65,7 +64,7 @@ public class NoGuiEngine implements GraphicEngine { } @Override - public void start(RenderingLoop d) {} + public void start(final RenderingLoop d) {} @Override public void repaint() {} @@ -79,62 +78,62 @@ public class NoGuiEngine implements GraphicEngine { } @Override - public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth, - float uvHeight) {} + public void glFillRect(final float x, final float y, final float width, final float height, final float uvX, + final float uvY, final float uvWidth, final float uvHeight) {} @Override - public void glFillColor(float x, float y, float width, float height) {} + public void glFillColor(final float x, final float y, final float width, final float height) {} @Override - public void glDrawStringRight(float x, float y, String text) {} + public void glDrawStringRight(final float x, final float y, final String text) {} @Override - public void glDrawStringLeft(float x, float y, String text) {} + public void glDrawStringLeft(final float x, final float y, final String text) {} @Override - public void glDrawStringCenter(float x, float y, String text) {} + public void glDrawStringCenter(final float x, final float y, final String text) {} @Override - public void glDrawLine(float x0, float y0, float x1, float y1) {} + public void glDrawLine(final float x0, final float y0, final float x1, final float y1) {} @Override - public void glDrawCharRight(int x, int y, char ch) {} + public void glDrawCharRight(final int x, final int y, final char ch) {} @Override - public void glDrawCharLeft(int x, int y, char ch) {} + public void glDrawCharLeft(final int x, final int y, final char ch) {} @Override - public void glDrawCharCenter(int x, int y, char ch) {} + public void glDrawCharCenter(final int x, final int y, final char ch) {} @Override - public void glColor4i(int red, int green, int blue, int alpha) {} + public void glColor4i(final int red, final int green, final int blue, final int alpha) {} @Override - public void glColor4f(float red, float green, float blue, float alpha) {} + public void glColor4f(final float red, final float green, final float blue, final float alpha) {} @Override - public void glColor3i(int r, int gg, int b) {} + public void glColor3i(final int r, final int gg, final int b) {} @Override - public void glColor3f(float red, float green, float blue) {} + public void glColor3f(final float red, final float green, final float blue) {} @Override - public void glColor(int c) {} + public void glColor(final int c) {} @Override public void glClearSkin() {} @Override - public void glClearColor4i(int red, int green, int blue, int alpha) {} + public void glClearColor4i(final int red, final int green, final int blue, final int alpha) {} @Override - public void glClearColor4f(float red, float green, float blue, float alpha) {} + public void glClearColor4f(final float red, final float green, final float blue, final float alpha) {} @Override - public void glClearColor(int c) {} + public void glClearColor(final int c) {} @Override - public void glClear(int screenWidth, int screenHeight) {} + public void glClear(final int screenWidth, final int screenHeight) {} @Override public BinaryFont getCurrentFont() { @@ -144,13 +143,13 @@ public class NoGuiEngine implements GraphicEngine { } @Override - public BinaryFont loadFont(String fontName) throws IOException { + public BinaryFont loadFont(final String fontName) throws IOException { return new BinaryFont() { @Override - public void use(GraphicEngine d) {} + public void use(final GraphicEngine d) {} @Override - public void load(String file) throws IOException {} + public void load(final String file) throws IOException {} @Override public boolean isInitialized() { @@ -158,10 +157,10 @@ public class NoGuiEngine implements GraphicEngine { } @Override - public void initialize(GraphicEngine d) {} + public void initialize(final GraphicEngine d) {} @Override - public int getStringWidth(String text) { + public int getStringWidth(final String text) { return 1; } @@ -190,13 +189,13 @@ public class NoGuiEngine implements GraphicEngine { } @Override - public BinaryFont loadFont(String path, String fontName) throws IOException { + public BinaryFont loadFont(final String path, final String fontName) throws IOException { return new BinaryFont() { @Override - public void use(GraphicEngine d) {} + public void use(final GraphicEngine d) {} @Override - public void load(String file) throws IOException {} + public void load(final String file) throws IOException {} @Override public boolean isInitialized() { @@ -204,10 +203,10 @@ public class NoGuiEngine implements GraphicEngine { } @Override - public void initialize(GraphicEngine d) {} + public void initialize(final GraphicEngine d) {} @Override - public int getStringWidth(String text) { + public int getStringWidth(final String text) { return 1; } @@ -236,13 +235,13 @@ public class NoGuiEngine implements GraphicEngine { } @Override - public Skin loadSkin(String file) throws IOException { + public Skin loadSkin(final String file) throws IOException { return new Skin() { @Override - public void use(GraphicEngine d) {} + public void use(final GraphicEngine d) {} @Override - public void load(String file) throws IOException {} + public void load(final String file) throws IOException {} @Override public boolean isInitialized() { @@ -250,7 +249,7 @@ public class NoGuiEngine implements GraphicEngine { } @Override - public void initialize(GraphicEngine d) {} + public void initialize(final GraphicEngine d) {} @Override public int getSkinWidth() { diff --git a/core/src/main/java/it/cavallium/warppi/gui/screens/ChooseVariableValueScreen.java b/core/src/main/java/it/cavallium/warppi/gui/screens/ChooseVariableValueScreen.java index 43108f04..57b66fbe 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/screens/ChooseVariableValueScreen.java +++ b/core/src/main/java/it/cavallium/warppi/gui/screens/ChooseVariableValueScreen.java @@ -13,7 +13,7 @@ public class ChooseVariableValueScreen extends Screen { private final MathInputScreen es; public Function resultNumberValue; - public ChooseVariableValueScreen(MathInputScreen es, VariableValue variableValue) { + public ChooseVariableValueScreen(final MathInputScreen es, final VariableValue variableValue) { super(); canBeInHistory = false; @@ -46,7 +46,7 @@ public class ChooseVariableValueScreen extends Screen { } @Override - public void beforeRender(float dt) { + public void beforeRender(final float dt) { } @@ -56,7 +56,7 @@ public class ChooseVariableValueScreen extends Screen { } @Override - public boolean onKeyPressed(KeyPressedEvent k) { + public boolean onKeyPressed(final KeyPressedEvent k) { switch (k.getKey()) { case LETTER_X: // PIDisplay.INSTANCE.goBack(); diff --git a/core/src/main/java/it/cavallium/warppi/gui/screens/EmptyScreen.java b/core/src/main/java/it/cavallium/warppi/gui/screens/EmptyScreen.java index c15c0c0a..314c9be1 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/screens/EmptyScreen.java +++ b/core/src/main/java/it/cavallium/warppi/gui/screens/EmptyScreen.java @@ -24,7 +24,7 @@ public class EmptyScreen extends Screen { } @Override - public void beforeRender(float dt) { + public void beforeRender(final float dt) { } diff --git a/core/src/main/java/it/cavallium/warppi/gui/screens/KeyboardDebugScreen.java b/core/src/main/java/it/cavallium/warppi/gui/screens/KeyboardDebugScreen.java index 3154a5a8..298ca011 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/screens/KeyboardDebugScreen.java +++ b/core/src/main/java/it/cavallium/warppi/gui/screens/KeyboardDebugScreen.java @@ -36,17 +36,15 @@ public class KeyboardDebugScreen extends Screen { Engine.INSTANCE.getHardwareDevice().getDisplayManager().fonts[2].use(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine); renderer.glColor4f(0.0f, 0.0f, 0.0f, 1.0f); renderer.glDrawStringLeft(10, 30, "Key position"); - renderer.glDrawStringLeft(10, 45, "X: " + keyX + ", Y:" + keyY); + renderer.glDrawStringLeft(10, 45, "X: " + KeyboardDebugScreen.keyX + ", Y:" + KeyboardDebugScreen.keyY); renderer.glDrawStringLeft(10, 65, "Key value"); renderer.glDrawStringLeft(10, 80, key); } Engine.INSTANCE.getHardwareDevice().getDisplayManager().fonts[3].use(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine); renderer.glColor4f(0.0f, 0.0f, 0.0f, 1.0f); - for (int i = 0; i < 5; i++) { - if (log[i] != null) { - renderer.glDrawStringLeft(10, 230 + 15 * (i + 1), log[i].toUpperCase()); - } - } + for (int i = 0; i < 5; i++) + if (KeyboardDebugScreen.log[i] != null) + renderer.glDrawStringLeft(10, 230 + 15 * (i + 1), KeyboardDebugScreen.log[i].toUpperCase()); //FROM SERIAL renderer.glColor4f(0.0f, 0.0f, 0.0f, 1.0f); @@ -54,44 +52,41 @@ public class KeyboardDebugScreen extends Screen { renderer.glFillColor(-80 + 100, 100, 200, 70); Engine.INSTANCE.getHardwareDevice().getDisplayManager().fonts[2].use(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine); renderer.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); - renderer.glDrawStringCenter(-80 + 100 + 200 / 2, 100 + 70 / 2 - (renderer.getCurrentFont().getCharacterHeight() / 2), "FROM SERIAL"); + renderer.glDrawStringCenter(-80 + 100 + 200 / 2, 100 + 70 / 2 - renderer.getCurrentFont().getCharacterHeight() / 2, "FROM SERIAL"); Engine.INSTANCE.getHardwareDevice().getDisplayManager().fonts[3].use(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine); renderer.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); for (int i = 0; i < 8; i++) { - if (pinsA[i] == 1) { + if (KeyboardDebugScreen.pinsA[i] == 1) renderer.glColor4f(0.0f, 1.0f, 0.0f, 1.0f); - } else if (pinsA[i] == 2) { + else if (KeyboardDebugScreen.pinsA[i] == 2) renderer.glColor4f(0.5f, 0.5f, 1.0f, 1.0f); - } else if (pinsA[i] == -1) { + else if (KeyboardDebugScreen.pinsA[i] == -1) renderer.glColor4f(0.7f, 0.7f, 0.7f, 1.0f); - } else if (pinsA[i] == 0) { + else if (KeyboardDebugScreen.pinsA[i] == 0) renderer.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); - } renderer.glFillColor(-80 + 103 + 25 * (7 - i), 80, 20, 20); renderer.glColor4f(0.0f, 0.0f, 0.0f, 1.0f); - renderer.glDrawStringCenter(-80 + 113 + 25 * (7 - i), 90 - (renderer.getCurrentFont().getCharacterHeight() / 2), "" + (i + 1)); + renderer.glDrawStringCenter(-80 + 113 + 25 * (7 - i), 90 - renderer.getCurrentFont().getCharacterHeight() / 2, "" + (i + 1)); } for (int i = 15; i >= 8; i--) { - if (pinsA[i] == 1) { + if (KeyboardDebugScreen.pinsA[i] == 1) renderer.glColor4f(0.0f, 1.0f, 0.0f, 1.0f); - } else if (pinsA[i] == 2) { + else if (KeyboardDebugScreen.pinsA[i] == 2) renderer.glColor4f(0.5f, 0.5f, 1.0f, 1.0f); - } else if (pinsA[i] == -1) { + else if (KeyboardDebugScreen.pinsA[i] == -1) renderer.glColor4f(0.7f, 0.7f, 0.7f, 1.0f); - } else if (pinsA[i] == 0) { + else if (KeyboardDebugScreen.pinsA[i] == 0) renderer.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); - } renderer.glFillColor(-80 + 103 + 25 * (i - 8), 170, 20, 20); renderer.glColor4f(0.0f, 0.0f, 0.0f, 1.0f); - renderer.glDrawStringCenter(-80 + 113 + 25 * (i - 8), 180 - (renderer.getCurrentFont().getCharacterHeight() / 2), "" + (i + 1)); + renderer.glDrawStringCenter(-80 + 113 + 25 * (i - 8), 180 - renderer.getCurrentFont().getCharacterHeight() / 2, "" + (i + 1)); } for (int i = 0; i < 8; i++) { - if (dataA[i]) { + if (KeyboardDebugScreen.dataA[i]) renderer.glColor4f(0.0f, 1.0f, 0.0f, 1.0f); - } else { + else renderer.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); - } - renderer.glFillColor(-80 + 160 + 10 * (i), 150, 8, 8); + renderer.glFillColor(-80 + 160 + 10 * i, 150, 8, 8); } //TO SERIAL @@ -100,57 +95,53 @@ public class KeyboardDebugScreen extends Screen { renderer.glFillColor(150 + 100, 100, 200, 70); Engine.INSTANCE.getHardwareDevice().getDisplayManager().fonts[2].use(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine); renderer.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); - renderer.glDrawStringCenter(150 + 100 + 200 / 2, 100 + 70 / 2 - (renderer.getCurrentFont().getCharacterHeight() / 2), "TO SERIAL"); + renderer.glDrawStringCenter(150 + 100 + 200 / 2, 100 + 70 / 2 - renderer.getCurrentFont().getCharacterHeight() / 2, "TO SERIAL"); Engine.INSTANCE.getHardwareDevice().getDisplayManager().fonts[3].use(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine); renderer.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); for (int i = 15; i >= 8; i--) { - if (pinsB[i] == 1) { + if (KeyboardDebugScreen.pinsB[i] == 1) renderer.glColor4f(0.0f, 1.0f, 0.0f, 1.0f); - } else if (pinsB[i] == 2) { + else if (KeyboardDebugScreen.pinsB[i] == 2) renderer.glColor4f(0.5f, 0.5f, 1.0f, 1.0f); - } else if (pinsB[i] == -1) { + else if (KeyboardDebugScreen.pinsB[i] == -1) renderer.glColor4f(0.7f, 0.7f, 0.7f, 1.0f); - } else if (pinsB[i] == 0) { + else if (KeyboardDebugScreen.pinsB[i] == 0) renderer.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); - } renderer.glFillColor(150 + 103 + 25 * (15 - i), 80, 20, 20); renderer.glColor4f(0.0f, 0.0f, 0.0f, 1.0f); - renderer.glDrawStringCenter(150 + 113 + 25 * (15 - i), 90 - (renderer.getCurrentFont().getCharacterHeight() / 2), "" + (i + 1)); + renderer.glDrawStringCenter(150 + 113 + 25 * (15 - i), 90 - renderer.getCurrentFont().getCharacterHeight() / 2, "" + (i + 1)); } for (int i = 7; i >= 0; i--) { - if (pinsB[i] == 1) { + if (KeyboardDebugScreen.pinsB[i] == 1) renderer.glColor4f(0.0f, 1.0f, 0.0f, 1.0f); - } else if (pinsB[i] == 2) { + else if (KeyboardDebugScreen.pinsB[i] == 2) renderer.glColor4f(0.5f, 0.5f, 1.0f, 1.0f); - } else if (pinsB[i] == -1) { + else if (KeyboardDebugScreen.pinsB[i] == -1) renderer.glColor4f(0.7f, 0.7f, 0.7f, 1.0f); - } else if (pinsB[i] == 0) { + else if (KeyboardDebugScreen.pinsB[i] == 0) renderer.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); - } - renderer.glFillColor(150 + 103 + 25 * (i), 170, 20, 20); + renderer.glFillColor(150 + 103 + 25 * i, 170, 20, 20); renderer.glColor4f(0.0f, 0.0f, 0.0f, 1.0f); - renderer.glDrawStringCenter(150 + 113 + 25 * (i), 180 - (renderer.getCurrentFont().getCharacterHeight() / 2), "" + (i + 1)); + renderer.glDrawStringCenter(150 + 113 + 25 * i, 180 - renderer.getCurrentFont().getCharacterHeight() / 2, "" + (i + 1)); } for (int i = 0; i < 8; i++) { - if (dataB[i]) { + if (KeyboardDebugScreen.dataB[i]) renderer.glColor4f(0.0f, 1.0f, 0.0f, 1.0f); - } else { + else renderer.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); - } - renderer.glFillColor(150 + 160 + 10 * (i), 150, 8, 8); + renderer.glFillColor(150 + 160 + 10 * i, 150, 8, 8); } //GPIO for (int i = 0; i < 40; i++) { - if (gpio[i] == true) { + if (KeyboardDebugScreen.gpio[i] == true) renderer.glColor4f(0.0f, 1.0f, 0.0f, 1.0f); - } else { + else renderer.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); - } if (i % 2 == 0) { - renderer.glFillColor(53 + 15 * ((i) / 2), 50, 5, 5); + renderer.glFillColor(53 + 15 * (i / 2), 50, 5, 5); renderer.glColor4f(0.0f, 0.0f, 0.0f, 1.0f); - renderer.glDrawStringCenter(55 + 15 * ((i) / 2), 60, "" + (i + 1)); + renderer.glDrawStringCenter(55 + 15 * (i / 2), 60, "" + (i + 1)); } else { renderer.glFillColor(53 + 15 * ((i - 1) / 2), 40, 5, 5); renderer.glColor4f(0.0f, 0.0f, 0.0f, 1.0f); @@ -159,24 +150,22 @@ public class KeyboardDebugScreen extends Screen { } //KEYS - for (int c = 0; c < 8; c++) { + for (int c = 0; c < 8; c++) for (int r = 0; r < 8; r++) { - if (ks[c][r]) { + if (KeyboardDebugScreen.ks[c][r]) renderer.glColor4f(0.0f, 1.0f, 0.0f, 1.0f); - } else { + else renderer.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); - } renderer.glFillColor(250 + 6 * c, 250 + 6 * r, 5, 5); } - } } @Override - public void beforeRender(float dt) { + public void beforeRender(final float dt) { if (System.currentTimeMillis() - beforetime >= 1000) { keyevent = "NONE"; - keyX = 0; - keyY = 0; + KeyboardDebugScreen.keyX = 0; + KeyboardDebugScreen.keyY = 0; key = ""; } } @@ -187,21 +176,21 @@ public class KeyboardDebugScreen extends Screen { } @Override - public boolean onKeyPressed(KeyPressedEvent k) { + public boolean onKeyPressed(final KeyPressedEvent k) { beforetime = System.currentTimeMillis(); keyevent = "PRESSED"; - keyX = 0; - keyY = 0; + KeyboardDebugScreen.keyX = 0; + KeyboardDebugScreen.keyY = 0; key = k.toString(); return false; } @Override - public boolean onKeyReleased(KeyReleasedEvent k) { + public boolean onKeyReleased(final KeyReleasedEvent k) { beforetime = System.currentTimeMillis(); keyevent = "RELEASED"; - keyX = 0; - keyY = 0; + KeyboardDebugScreen.keyX = 0; + KeyboardDebugScreen.keyY = 0; key = k.toString(); return false; } @@ -213,13 +202,12 @@ public class KeyboardDebugScreen extends Screen { public static boolean[][] ks = new boolean[8][8]; public static boolean[] gpio = new boolean[40]; - public static void log(String str) { - final String[] newlog = log; - for (int i = 1; i < 5; i++) { + public static void log(final String str) { + final String[] newlog = KeyboardDebugScreen.log; + for (int i = 1; i < 5; i++) newlog[i - 1] = newlog[i]; - } newlog[4] = "[" + System.currentTimeMillis() + "]" + str; - log = newlog; + KeyboardDebugScreen.log = newlog; } } diff --git a/core/src/main/java/it/cavallium/warppi/gui/screens/LoadingScreen.java b/core/src/main/java/it/cavallium/warppi/gui/screens/LoadingScreen.java index 4e96f183..ee5864fb 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/screens/LoadingScreen.java +++ b/core/src/main/java/it/cavallium/warppi/gui/screens/LoadingScreen.java @@ -32,7 +32,7 @@ public class LoadingScreen extends Screen { } @Override - public void beforeRender(float dt) { + public void beforeRender(final float dt) { loadingTextTranslation = GraphicUtils.sinDeg(endLoading * 90f) * 10f; endLoading += dt; @@ -60,9 +60,8 @@ public class LoadingScreen extends Screen { if (mustRefresh) { mustRefresh = false; return true; - } else { + } else return false; - } } } diff --git a/core/src/main/java/it/cavallium/warppi/gui/screens/MarioScreen.java b/core/src/main/java/it/cavallium/warppi/gui/screens/MarioScreen.java index 95f693cb..bc4c9406 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/screens/MarioScreen.java +++ b/core/src/main/java/it/cavallium/warppi/gui/screens/MarioScreen.java @@ -44,35 +44,30 @@ public class MarioScreen extends Screen { @Override public void initialized() { try { - if (skin == null) { - skin = Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.loadSkin("marioskin.png"); - } - if (groundskin == null) { - groundskin = Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.loadSkin("marioground.png"); - } - if (gpuTest2 == null) { + if (MarioScreen.skin == null) + MarioScreen.skin = Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.loadSkin("marioskin.png"); + if (MarioScreen.groundskin == null) + MarioScreen.groundskin = Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.loadSkin("marioground.png"); + if (MarioScreen.gpuTest2 == null) try { - gpuTest2 = Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.loadFont("gputest2"); + MarioScreen.gpuTest2 = Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.loadFont("gputest2"); } catch (final Exception ex) {} - } - if (gpuTest1 == null) { + if (MarioScreen.gpuTest1 == null) try { - gpuTest1 = Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.loadFont("gputest12"); - gpuTest12 = true; + MarioScreen.gpuTest1 = Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.loadFont("gputest12"); + MarioScreen.gpuTest12 = true; } catch (final Exception ex) { - gpuTest12 = false; + MarioScreen.gpuTest12 = false; try { - gpuTest1 = Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.loadFont("gputest1"); + MarioScreen.gpuTest1 = Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.loadFont("gputest1"); } catch (final Exception ex2) {} } - } - if (gpuTest3 == null) { + if (MarioScreen.gpuTest3 == null) try { - gpuTest3 = Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.loadSkin("font_gputest3.png"); + MarioScreen.gpuTest3 = Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.loadSkin("font_gputest3.png"); } catch (final Exception ex) { ex.printStackTrace(); } - } } catch (final IOException e) { e.printStackTrace(); } @@ -80,13 +75,12 @@ public class MarioScreen extends Screen { @Override public void created() throws InterruptedException { - if (!errored) { + if (!errored) g = new MarioGame(); - } } @Override - public void beforeRender(float dt) { + public void beforeRender(final float dt) { if (!errored) { final boolean rightPressed = Keyboard.isKeyDown(2, 5); final boolean leftPressed = Keyboard.isKeyDown(2, 3); @@ -111,13 +105,13 @@ public class MarioScreen extends Screen { @Override public void render() { - if (errored) { + if (errored) Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawStringLeft(0, 20, "ERROR"); - } else { - if (groundskin != null) { + else { + if (MarioScreen.groundskin != null) { final double playerX = g.getPlayer().getX(); final double playerY = g.getPlayer().getY(); - groundskin.use(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine); + MarioScreen.groundskin.use(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine); final MarioWorld w = g.getCurrentWorld(); final int width = w.getWidth(); final int height = w.getHeight(); @@ -126,11 +120,11 @@ public class MarioScreen extends Screen { final float shiftX = -8 + 16 * (float) playerX; final float shiftY = -8 + 16 * (height - (float) playerY); int blue = -1; - for (int ix = 0; ix < width; ix++) { + for (int ix = 0; ix < width; ix++) for (int iy = 0; iy < height; iy++) { final double distX = Math.abs(playerX - ix); final double distY = Math.abs(playerY - iy - 1.5d); - if ((distX * distX + distY * distY / 2d) < 25d) { + if (distX * distX + distY * distY / 2d < 25d) { final byte b = w.getBlockIdAt(ix, iy); if (b == 0) { if (blue != 1) { @@ -147,47 +141,46 @@ public class MarioScreen extends Screen { } } } - } if (blue != 0) { blue = 0; Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glColor(0xffffffff); } //DRAW MARIO - skin.use(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine); + MarioScreen.skin.use(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine); Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glFillRect(screenX - (g.getPlayer().flipped ? 3 : 0), screenY, 35, 27, 35 * (g.getPlayer().marioSkinPos[0] + (g.getPlayer().flipped ? 2 : 1)), 27 * g.getPlayer().marioSkinPos[1], 35 * (g.getPlayer().flipped ? -1 : 1), 27); // PIDisplay.renderer.glDrawSkin(getPosX() - 18, 25 + getPosY(), 35 * (marioSkinPos[0] + (flipped ? 2 : 1)), 27 * marioSkinPos[1], 35 * (marioSkinPos[0] + (flipped ? 1 : 2)), 27 * (marioSkinPos[1] + 1), true); } // GPU PERFORMANCE TEST - if (gpuTest1 != null) { + if (MarioScreen.gpuTest1 != null) { Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glColor3f(1, 1, 1); - Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glFillColor(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getWidth() - (gpuTest12 ? 512 : 256), Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getHeight() / 2 - (gpuTest12 ? 256 : 128), gpuTest12 ? 512 : 256, gpuTest12 ? 512 : 256); - gpuTest1.use(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine); + Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glFillColor(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getWidth() - (MarioScreen.gpuTest12 ? 512 : 256), Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getHeight() / 2 - (MarioScreen.gpuTest12 ? 256 : 128), MarioScreen.gpuTest12 ? 512 : 256, MarioScreen.gpuTest12 ? 512 : 256); + MarioScreen.gpuTest1.use(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine); Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glColor3f(0, 0, 0); - Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawStringRight(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getWidth(), Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getHeight() / 2 - (gpuTest12 ? 256 : 128), gpuCharTest1[gpuCharTest1Num]); + Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawStringRight(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getWidth(), Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getHeight() / 2 - (MarioScreen.gpuTest12 ? 256 : 128), gpuCharTest1[gpuCharTest1Num]); } - if (gpuTest3 != null) { - gpuTest3.use(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine); + if (MarioScreen.gpuTest3 != null) { + MarioScreen.gpuTest3.use(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine); Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glColor4f(1, 1, 1, 0.7f); Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glFillRect(0, StaticVars.screenSize[1] - 128, 224, 128, gpuTestNum * 224, 0, 224, 128); } - if (gpuTest2 != null) { - gpuTest2.use(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine); + if (MarioScreen.gpuTest2 != null) { + MarioScreen.gpuTest2.use(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine); Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glColor(0xFF000000); - Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawStringRight(StaticVars.screenSize[0], Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getHeight() - gpuTest2.getCharacterHeight(), "A"); + Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawStringRight(StaticVars.screenSize[0], Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getHeight() - MarioScreen.gpuTest2.getCharacterHeight(), "A"); Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glColor(0xFF800000); - Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawStringRight(StaticVars.screenSize[0], Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getHeight() - gpuTest2.getCharacterHeight(), "B"); + Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawStringRight(StaticVars.screenSize[0], Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getHeight() - MarioScreen.gpuTest2.getCharacterHeight(), "B"); Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glColor(0xFFeea28e); - Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawStringRight(StaticVars.screenSize[0], Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getHeight() - gpuTest2.getCharacterHeight(), "C"); + Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawStringRight(StaticVars.screenSize[0], Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getHeight() - MarioScreen.gpuTest2.getCharacterHeight(), "C"); Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glColor(0xFFee7255); - Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawStringRight(StaticVars.screenSize[0], Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getHeight() - gpuTest2.getCharacterHeight(), "D"); + Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawStringRight(StaticVars.screenSize[0], Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getHeight() - MarioScreen.gpuTest2.getCharacterHeight(), "D"); Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glColor(0xFFeac0b0); - Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawStringRight(StaticVars.screenSize[0], Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getHeight() - gpuTest2.getCharacterHeight(), "E"); + Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawStringRight(StaticVars.screenSize[0], Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getHeight() - MarioScreen.gpuTest2.getCharacterHeight(), "E"); Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glColor(0xFFf3d8ce); - Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawStringRight(StaticVars.screenSize[0], Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getHeight() - gpuTest2.getCharacterHeight(), "F"); + Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawStringRight(StaticVars.screenSize[0], Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getHeight() - MarioScreen.gpuTest2.getCharacterHeight(), "F"); Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glColor(0xFFffede7); - Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawStringRight(StaticVars.screenSize[0], Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getHeight() - gpuTest2.getCharacterHeight(), "G"); + Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glDrawStringRight(StaticVars.screenSize[0], Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getHeight() - MarioScreen.gpuTest2.getCharacterHeight(), "G"); } } } diff --git a/core/src/main/java/it/cavallium/warppi/gui/screens/MathInputScreen.java b/core/src/main/java/it/cavallium/warppi/gui/screens/MathInputScreen.java index 8f3638ce..b9bd556b 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/screens/MathInputScreen.java +++ b/core/src/main/java/it/cavallium/warppi/gui/screens/MathInputScreen.java @@ -83,15 +83,13 @@ public class MathInputScreen extends Screen { } @Override - public void beforeRender(float dt) { - if (Engine.INSTANCE.getHardwareDevice().getDisplayManager().error == null) { + public void beforeRender(final float dt) { + if (Engine.INSTANCE.getHardwareDevice().getDisplayManager().error == null) Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glClearColor(0xFFc5c2af); - } else { + else Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer.glClearColor(0xFFDC3C32); - } - if (userInput.beforeRender(dt)) { + if (userInput.beforeRender(dt)) mustRefresh = true; - } if (computingResult) { computingElapsedTime += dt; computingAnimationElapsedTime += dt; @@ -100,9 +98,8 @@ public class MathInputScreen extends Screen { computingAnimationIndex = (computingAnimationIndex + 1) % 16; mustRefresh = true; } - if (computingElapsedTime > 5) { + if (computingElapsedTime > 5) computingBreakTipVisible = true; - } } else { computingElapsedTime = 0; computingAnimationElapsedTime = 0; @@ -114,7 +111,7 @@ public class MathInputScreen extends Screen { @Override public void render() { final Renderer renderer = Engine.INSTANCE.getHardwareDevice().getDisplayManager().renderer; - fontBig.use(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine); + MathInputScreen.fontBig.use(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine); final int textColor = 0xFF000000; final int padding = 4; renderer.glColor(textColor); @@ -134,11 +131,8 @@ public class MathInputScreen extends Screen { renderer.glColor3f(0.75f, 0, 0); renderer.glDrawStringRight(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getWidth() - 4 - size - 4, Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getHeight() - size / 2 - renderer.getCurrentFont().getCharacterHeight() / 2 - 4, "Press (=) to stop"); } - } else { - if (!result.isContentEmpty()) { - result.draw(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine, renderer, Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getWidth() - result.getWidth() - 2, Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getHeight() - result.getHeight() - 2); - } - } + } else if (!result.isContentEmpty()) + result.draw(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine, renderer, Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getWidth() - result.getWidth() - 2, Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.getHeight() - result.getHeight() - 2); } @Override @@ -148,11 +142,10 @@ public class MathInputScreen extends Screen { final int pos = 2; final int spacersNumb = 1; int skinN = 0; - if (calc.exactMode) { + if (calc.exactMode) skinN = 22; - } else { + else skinN = 21; - } Engine.INSTANCE.getHardwareDevice().getDisplayManager().guiSkin.use(Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine); renderer.glFillRect(2 + 18 * pos + 2 * spacersNumb, 2, 16, 16, 16 * skinN, 16 * 0, 16, 16); } @@ -162,13 +155,12 @@ public class MathInputScreen extends Screen { if (mustRefresh) { mustRefresh = false; return true; - } else { + } else return false; - } } @Override - public boolean onKeyPressed(KeyPressedEvent k) { + public boolean onKeyPressed(final KeyPressedEvent k) { Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_MIN, "MathInputScreen", "Pressed key " + k.getKey().toString()); try { switch (k.getKey()) { @@ -200,9 +192,8 @@ public class MathInputScreen extends Screen { case STEP: currentStep++; case SIMPLIFY: - if (!step) { + if (!step) currentStep = 0; - } if (Engine.INSTANCE.getHardwareDevice().getDisplayManager().error != null) { //TODO: make the error management a global API rather than being relegated to this screen. Engine.getPlatform().getConsoleUtils().out().println(1, "Resetting after error..."); @@ -211,65 +202,61 @@ public class MathInputScreen extends Screen { calc.f2 = null; calc.resultsCount = 0; return true; - } else { - if (!computingResult) { - computingResult = true; - computingThread = new Thread(() -> { + } else if (!computingResult) { + computingResult = true; + computingThread = new Thread(() -> { + try { try { - try { - if (!userInput.isAlreadyParsed() && !userInput.isEmpty()) { - final Expression expr = MathParser.parseInput(calc, userInput); - if (calc.f == null | calc.f2 == null) { - calc.f = new ObjectArrayList<>(); - calc.f2 = new ObjectArrayList<>(); - } else { - calc.f.clear(); - calc.f2.clear(); - } - calc.f.add(expr); - Engine.getPlatform().getConsoleUtils().out().println(2, "INPUT: " + expr); - final MathSolver ms = new MathSolver(expr); - final ObjectArrayList> resultSteps = ms.solveAllSteps(); - resultSteps.add(0, Utils.newArrayList(expr)); - final ObjectArrayList resultExpressions = resultSteps.get(resultSteps.size() - 1); - for (final Function rr : resultExpressions) { - Engine.getPlatform().getConsoleUtils().out().println(0, "RESULT: " + rr.toString()); - } - final ObjectArrayList> resultBlocks = MathParser.parseOutput(calc, resultExpressions); - result.setContentAsMultipleGroups(resultBlocks); - // showVariablesDialog(() -> { - // currentExpression = newExpression; - // simplify(); - // }); + if (!userInput.isAlreadyParsed() && !userInput.isEmpty()) { + final Expression expr = MathParser.parseInput(calc, userInput); + if (calc.f == null | calc.f2 == null) { + calc.f = new ObjectArrayList<>(); + calc.f2 = new ObjectArrayList<>(); + } else { + calc.f.clear(); + calc.f2.clear(); } - } catch (final InterruptedException ex) { - Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_MIN, "Computing thread stopped."); - } catch (final Exception ex) { - if (Engine.getPlatform().getSettings().isDebugEnabled()) { - ex.printStackTrace(); - } - throw new Error(Errors.SYNTAX_ERROR); + calc.f.add(expr); + Engine.getPlatform().getConsoleUtils().out().println(2, "INPUT: " + expr); + final MathSolver ms = new MathSolver(expr); + final ObjectArrayList> resultSteps = ms.solveAllSteps(); + resultSteps.add(0, Utils.newArrayList(expr)); + final ObjectArrayList resultExpressions = resultSteps.get(resultSteps.size() - 1); + for (final Function rr : resultExpressions) + Engine.getPlatform().getConsoleUtils().out().println(0, "RESULT: " + rr.toString()); + final ObjectArrayList> resultBlocks = MathParser.parseOutput(calc, resultExpressions); + result.setContentAsMultipleGroups(resultBlocks); + // showVariablesDialog(() -> { + // currentExpression = newExpression; + // simplify(); + // }); } - } catch (final Error e) { - d.errorStackTrace = Engine.getPlatform().stacktraceToString(e); - Engine.INSTANCE.getHardwareDevice().getDisplayManager().error = e.id.toString(); - System.err.println(e.id); + } catch (final InterruptedException ex) { + Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_MIN, "Computing thread stopped."); + } catch (final Exception ex) { + if (Engine.getPlatform().getSettings().isDebugEnabled()) + ex.printStackTrace(); + throw new Error(Errors.SYNTAX_ERROR); } - computingResult = false; - }); - Engine.getPlatform().setThreadName(computingThread, "Computing Thread"); - Engine.getPlatform().setThreadDaemon(computingThread); - computingThread.setPriority(Thread.NORM_PRIORITY + 3); - computingThread.start(); - return true; - } else { - if (computingThread != null) { - computingThread.interrupt(); - computingResult = false; - return true; + } catch (final Error e) { + d.errorStackTrace = Engine.getPlatform().stacktraceToString(e); + Engine.INSTANCE.getHardwareDevice().getDisplayManager().error = e.id.toString(); + System.err.println(e.id); } - return false; + computingResult = false; + }); + Engine.getPlatform().setThreadName(computingThread, "Computing Thread"); + Engine.getPlatform().setThreadDaemon(computingThread); + computingThread.setPriority(Thread.NORM_PRIORITY + 3); + computingThread.start(); + return true; + } else { + if (computingThread != null) { + computingThread.interrupt(); + computingResult = false; + return true; } + return false; } case NUM0: typeChar('0'); @@ -448,13 +435,12 @@ public class MathInputScreen extends Screen { } return false; case DRG_CYCLE: - if (calc.angleMode.equals(AngleMode.DEG) == true) { + if (calc.angleMode.equals(AngleMode.DEG) == true) calc.angleMode = AngleMode.RAD; - } else if (calc.angleMode.equals(AngleMode.RAD) == true) { + else if (calc.angleMode.equals(AngleMode.RAD) == true) calc.angleMode = AngleMode.GRA; - } else { + else calc.angleMode = AngleMode.DEG; - } currentStep = 0; return true; default: @@ -470,7 +456,7 @@ public class MathInputScreen extends Screen { @SuppressWarnings("unused") @Deprecated - private ObjectArrayList solveExpression(ObjectArrayList f22) { + private ObjectArrayList solveExpression(final ObjectArrayList f22) { return null; /* try { @@ -519,7 +505,7 @@ public class MathInputScreen extends Screen { partialResults.clear(); } } - + if (results.size() == 0) { calc.resultsCount = 0; } else { @@ -561,7 +547,7 @@ public class MathInputScreen extends Screen { return; } } - + final ObjectArrayList results = solveExpression(calc.f); if (results.size() == 0) { calc.resultsCount = 0; @@ -596,7 +582,7 @@ public class MathInputScreen extends Screen { @Deprecated private void changeEquationScreen() { throw new UnsupportedOperationException(); -// +// // if (!userInput.isEmpty()) { // final MathInputScreen cloned = clone(); // cloned.userInput.setCaretPosition(cloned.userInput.getCaretMaxPosition()-1); @@ -607,25 +593,22 @@ public class MathInputScreen extends Screen { // } } - public void typeChar(char chr) { + public void typeChar(final char chr) { userInput.typeChar(chr); mustRefresh = true; } @Override - public boolean onKeyReleased(KeyReleasedEvent k) { - if (k.getKey() == Key.OK) { + public boolean onKeyReleased(final KeyReleasedEvent k) { + if (k.getKey() == Key.OK) return true; - } else { - if (userInput.isExtraOpened() && userInput.getExtraKeyboardEventListener().onKeyReleased(k)) { - return true; - } else { - switch (k.getKey()) { - default: - return false; - } + else if (userInput.isExtraOpened() && userInput.getExtraKeyboardEventListener().onKeyReleased(k)) + return true; + else + switch (k.getKey()) { + default: + return false; } - } } public void showVariablesDialog() { @@ -635,11 +618,9 @@ public class MathInputScreen extends Screen { public void showVariablesDialog(final Runnable runnable) { final Thread ct = new Thread(() -> { final ObjectArrayList knownVarsInFunctions = getKnownVariables(calc.f.toArray(new Function[calc.f.size()])); - for (final VariableValue f : calc.variablesValues) { - if (knownVarsInFunctions.contains(f.v)) { + for (final VariableValue f : calc.variablesValues) + if (knownVarsInFunctions.contains(f.v)) knownVarsInFunctions.remove(f.v); - } - } boolean cancelled = false; for (final Function f : knownVarsInFunctions) { @@ -653,19 +634,15 @@ public class MathInputScreen extends Screen { break; } else { final int is = calc.variablesValues.size(); - for (int i = 0; i < is; i++) { - if (calc.variablesValues.get(i).v == f) { + for (int i = 0; i < is; i++) + if (calc.variablesValues.get(i).v == f) calc.variablesValues.remove(i); - } - } calc.variablesValues.add(new VariableValue((Variable) f, (Number) cvs.resultNumberValue)); } } - if (!cancelled) { - if (runnable != null) { + if (!cancelled) + if (runnable != null) runnable.run(); - } - } }); Engine.getPlatform().setThreadName(ct, "Variables user-input queue thread"); ct.setPriority(Thread.MIN_PRIORITY); @@ -673,23 +650,19 @@ public class MathInputScreen extends Screen { ct.start(); } - private ObjectArrayList getKnownVariables(Function[] fncs) { + private ObjectArrayList getKnownVariables(final Function[] fncs) { final ObjectArrayList res = new ObjectArrayList<>(); - for (final Function f : fncs) { - if (f instanceof FunctionOperator) { + for (final Function f : fncs) + if (f instanceof FunctionOperator) res.addAll(getKnownVariables(new Function[] { ((FunctionOperator) f).getParameter1(), ((FunctionOperator) f).getParameter2() })); - } else if (f instanceof FunctionDynamic) { + else if (f instanceof FunctionDynamic) res.addAll(getKnownVariables(((FunctionDynamic) f).getParameters())); - } else if (f instanceof FunctionSingle) { + else if (f instanceof FunctionSingle) res.addAll(getKnownVariables(new Function[] { ((FunctionSingle) f).getParameter() })); - } else if (f instanceof Variable) { - if (((Variable) f).getType() == Variable.V_TYPE.CONSTANT) { - if (!res.contains(f)) { + else if (f instanceof Variable) + if (((Variable) f).getType() == Variable.V_TYPE.CONSTANT) + if (!res.contains(f)) res.add(f); - } - } - } - } return res; } diff --git a/core/src/main/java/it/cavallium/warppi/gui/screens/SolveForXScreen.java b/core/src/main/java/it/cavallium/warppi/gui/screens/SolveForXScreen.java index 07a66f28..0812c176 100644 --- a/core/src/main/java/it/cavallium/warppi/gui/screens/SolveForXScreen.java +++ b/core/src/main/java/it/cavallium/warppi/gui/screens/SolveForXScreen.java @@ -9,7 +9,7 @@ public class SolveForXScreen extends Screen { @SuppressWarnings("unused") private final MathInputScreen es; - public SolveForXScreen(MathInputScreen es) { + public SolveForXScreen(final MathInputScreen es) { super(); canBeInHistory = false; @@ -33,7 +33,7 @@ public class SolveForXScreen extends Screen { } @Override - public void beforeRender(float dt) { + public void beforeRender(final float dt) { } @@ -43,7 +43,7 @@ public class SolveForXScreen extends Screen { } @Override - public boolean onKeyPressed(KeyPressedEvent k) { + public boolean onKeyPressed(final KeyPressedEvent k) { switch (k.getKey()) { case LETTER_X: //TODO: far funzionare questa parte diff --git a/core/src/main/java/it/cavallium/warppi/math/Function.java b/core/src/main/java/it/cavallium/warppi/math/Function.java index 84b66786..64390589 100644 --- a/core/src/main/java/it/cavallium/warppi/math/Function.java +++ b/core/src/main/java/it/cavallium/warppi/math/Function.java @@ -9,67 +9,67 @@ public interface Function { /** * Returns this function and its children in a string form. - * + * * @return This function and its children in a string form. */ @Override - public String toString(); + String toString(); @Override - public boolean equals(Object o); + boolean equals(Object o); /** * Deep clone this function. - * + * * @return A clone of this function. */ - public Function clone(); + Function clone(); /** * Generic method to change a parameter in a known position. - * + * * @param index * parameter index. * @param var * parameter. * @return A new instance of this function. */ - public Function setParameter(int index, Function var) throws IndexOutOfBoundsException; + Function setParameter(int index, Function var) throws IndexOutOfBoundsException; /** * Generic method to retrieve a parameter in a known position. - * + * * @param index * parameter index. * @return The requested parameter. */ - public Function getParameter(int index) throws IndexOutOfBoundsException; + Function getParameter(int index) throws IndexOutOfBoundsException; /** * Retrieve the current Math Context used by this function - * + * * @return Calculator mathContext */ - public MathContext getMathContext(); + MathContext getMathContext(); /** * Simplify the current function or it's children using the specified * rule - * + * * @param rule * @return A list of the resulting Functions if the rule is applicable and * something changed, null otherwise * @throws Error * @throws InterruptedException */ - public ObjectArrayList simplify(Rule rule) throws Error, InterruptedException; + ObjectArrayList simplify(Rule rule) throws Error, InterruptedException; /** - * + * * @param context * Mathematical Context * @return An ArrayList of parsed Blocks * @throws Error */ - public ObjectArrayList toBlock(MathContext context) throws Error; + ObjectArrayList toBlock(MathContext context) throws Error; } diff --git a/core/src/main/java/it/cavallium/warppi/math/FunctionDynamic.java b/core/src/main/java/it/cavallium/warppi/math/FunctionDynamic.java index df64571a..c25c6ac5 100644 --- a/core/src/main/java/it/cavallium/warppi/math/FunctionDynamic.java +++ b/core/src/main/java/it/cavallium/warppi/math/FunctionDynamic.java @@ -9,21 +9,20 @@ import it.cavallium.warppi.util.Utils; import it.unimi.dsi.fastutil.objects.ObjectArrayList; public abstract class FunctionDynamic implements Function { - public FunctionDynamic(MathContext root) { + public FunctionDynamic(final MathContext root) { this.root = root; functions = new Function[] {}; } - public FunctionDynamic(Function[] values) { - if (values.length > 0) { + public FunctionDynamic(final Function[] values) { + if (values.length > 0) root = values[0].getMathContext(); - } else { + else throw new NullPointerException("Nessun elemento nell'array. Impossibile ricavare il nodo root"); - } functions = values; } - public FunctionDynamic(MathContext root, Function[] values) { + public FunctionDynamic(final MathContext root, final Function[] values) { this.root = root; functions = values; } @@ -39,9 +38,8 @@ public abstract class FunctionDynamic implements Function { final FunctionDynamic f = clone(); final int vsize = value.size(); final Function[] tmp = new Function[vsize]; - for (int i = 0; i < vsize; i++) { + for (int i = 0; i < vsize; i++) tmp[i] = value.get(i); - } f.functions = tmp; return f; } @@ -53,18 +51,18 @@ public abstract class FunctionDynamic implements Function { } @Override - public Function getParameter(int index) { + public Function getParameter(final int index) { return functions[index]; } @Override - public FunctionDynamic setParameter(int index, Function value) { + public FunctionDynamic setParameter(final int index, final Function value) { final FunctionDynamic f = clone(); f.functions[index] = value; return f; } - public FunctionDynamic appendParameter(Function value) { + public FunctionDynamic appendParameter(final Function value) { final FunctionDynamic f = clone(); f.functions = Arrays.copyOf(f.functions, f.functions.length + 1); f.functions[f.functions.length - 1] = value; @@ -73,53 +71,49 @@ public abstract class FunctionDynamic implements Function { /** * Retrieve the current number of parameters. - * + * * @return The number of parameters. */ public int getParametersLength() { return functions.length; } - public FunctionDynamic setParametersLength(int length) { + public FunctionDynamic setParametersLength(final int length) { final FunctionDynamic f = clone(); f.functions = Arrays.copyOf(functions, length); return f; } @Override - public final ObjectArrayList simplify(Rule rule) throws Error, InterruptedException { + public final ObjectArrayList simplify(final Rule rule) throws Error, InterruptedException { final Function[] fncs = getParameters(); - if (Thread.interrupted()) { + if (Thread.interrupted()) throw new InterruptedException(); - } final ObjectArrayList result = new ObjectArrayList<>(); final ObjectArrayList> ln = new ObjectArrayList<>(); boolean alreadySolved = true; for (final Function fnc : fncs) { final ObjectArrayList l = new ObjectArrayList<>(); - if (Thread.interrupted()) { + if (Thread.interrupted()) throw new InterruptedException(); - } final ObjectArrayList simplifiedFnc = fnc.simplify(rule); - if (simplifiedFnc == null) { + if (simplifiedFnc == null) l.add(fnc); - } else { + else { l.addAll(simplifiedFnc); alreadySolved = false; } ln.add(l); } - if (alreadySolved) { + if (alreadySolved) return rule.execute(this); - } final Function[][] results = Utils.joinFunctionsResults(ln); - for (final Function[] f : results) { + for (final Function[] f : results) result.add(this.setParameters(f)); - } return result; } @@ -138,7 +132,7 @@ public abstract class FunctionDynamic implements Function { } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { return false; } } diff --git a/core/src/main/java/it/cavallium/warppi/math/FunctionOperator.java b/core/src/main/java/it/cavallium/warppi/math/FunctionOperator.java index 54b3a54f..ba1ded8c 100644 --- a/core/src/main/java/it/cavallium/warppi/math/FunctionOperator.java +++ b/core/src/main/java/it/cavallium/warppi/math/FunctionOperator.java @@ -11,7 +11,7 @@ public abstract class FunctionOperator implements Function { /** * Create a new instance of FunctionOperator. The Math Context will be the * same of value1's. - * + * * @throws NullPointerException * when value1 is null. * @param value1 @@ -19,7 +19,7 @@ public abstract class FunctionOperator implements Function { * @param value2 * The parameter of this function. */ - public FunctionOperator(Function value1, Function value2) throws NullPointerException { + public FunctionOperator(final Function value1, final Function value2) throws NullPointerException { mathContext = value1.getMathContext(); parameter1 = value1; parameter2 = value2; @@ -27,13 +27,13 @@ public abstract class FunctionOperator implements Function { /** * Create a new instance of FunctionOperator. - * + * * @param value1 * The parameter of this function. * @param value2 * The parameter of this function. */ - public FunctionOperator(MathContext mc, Function value1, Function value2) { + public FunctionOperator(final MathContext mc, final Function value1, final Function value2) { mathContext = mc; parameter1 = value1; parameter2 = value2; @@ -45,7 +45,7 @@ public abstract class FunctionOperator implements Function { protected Function parameter2 = null; /** - * + * * @return First parameter. */ public Function getParameter1() { @@ -53,7 +53,7 @@ public abstract class FunctionOperator implements Function { } /** - * + * * @return Second parameter. */ public Function getParameter2() { @@ -61,31 +61,31 @@ public abstract class FunctionOperator implements Function { } /** - * + * * @param var * First parameter. * @return A new instance of this function. */ - public FunctionOperator setParameter1(Function var) { + public FunctionOperator setParameter1(final Function var) { final FunctionOperator s = clone(); s.parameter1 = var; return s; } /** - * + * * @param var * Second parameter. * @return A new instance of this function. */ - public FunctionOperator setParameter2(Function var) { + public FunctionOperator setParameter2(final Function var) { final FunctionOperator s = clone(); s.parameter2 = var; return s; } @Override - public FunctionOperator setParameter(int index, Function var) throws IndexOutOfBoundsException { + public FunctionOperator setParameter(final int index, final Function var) throws IndexOutOfBoundsException { switch (index) { case 0: return setParameter1(var); @@ -97,7 +97,7 @@ public abstract class FunctionOperator implements Function { } @Override - public Function getParameter(int index) throws IndexOutOfBoundsException { + public Function getParameter(final int index) throws IndexOutOfBoundsException { switch (index) { case 0: return getParameter1(); @@ -114,58 +114,50 @@ public abstract class FunctionOperator implements Function { } @Override - public final ObjectArrayList simplify(Rule rule) throws Error, InterruptedException { - if (Thread.interrupted()) { + public final ObjectArrayList simplify(final Rule rule) throws Error, InterruptedException { + if (Thread.interrupted()) throw new InterruptedException(); - } final ObjectArrayList simplifiedParam1 = parameter1.simplify(rule); final ObjectArrayList simplifiedParam2 = parameter2.simplify(rule); try { - if (simplifiedParam1 == null & simplifiedParam2 == null) { + if (simplifiedParam1 == null & simplifiedParam2 == null) return rule.execute(this); - } } catch (final Exception e) { final Error err = new Error(Errors.ERROR, "Error while executing rule '" + rule.getRuleName() + "'!\n" + e.getMessage()); err.initCause(e); throw err; } - if (Thread.interrupted()) { + if (Thread.interrupted()) throw new InterruptedException(); - } final ObjectArrayList result = new ObjectArrayList<>(); final ObjectArrayList l1 = new ObjectArrayList<>(); final ObjectArrayList l2 = new ObjectArrayList<>(); - if (Thread.interrupted()) { + if (Thread.interrupted()) throw new InterruptedException(); - } - if (simplifiedParam1 == null) { + if (simplifiedParam1 == null) l1.add(parameter1); - } else { - if (Thread.interrupted()) { + else { + if (Thread.interrupted()) throw new InterruptedException(); - } l1.addAll(simplifiedParam1); } - if (Thread.interrupted()) { + if (Thread.interrupted()) throw new InterruptedException(); - } - if (simplifiedParam2 == null) { + if (simplifiedParam2 == null) l2.add(parameter2); - } else { - if (Thread.interrupted()) { + else { + if (Thread.interrupted()) throw new InterruptedException(); - } l2.addAll(simplifiedParam2); } final Function[][] results = Utils.joinFunctionsResults(l1, l2); - for (final Function[] f : results) { + for (final Function[] f : results) result.add(setParameter1(f[0]).setParameter2(f[1])); - } return result; } diff --git a/core/src/main/java/it/cavallium/warppi/math/FunctionSingle.java b/core/src/main/java/it/cavallium/warppi/math/FunctionSingle.java index 0a6f0810..ef53e3bf 100644 --- a/core/src/main/java/it/cavallium/warppi/math/FunctionSingle.java +++ b/core/src/main/java/it/cavallium/warppi/math/FunctionSingle.java @@ -9,37 +9,37 @@ public abstract class FunctionSingle implements Function { /** * Create a new instance of FunctionSingle. The Math Context will be the * same of value's. - * + * * @throws NullPointerException * when value is null. * @param value * The parameter of this function. */ - public FunctionSingle(Function value) throws NullPointerException { + public FunctionSingle(final Function value) throws NullPointerException { mathContext = value.getMathContext(); parameter = value; } /** * Create a new instance of FunctionSingle. - * + * * @param mathContext * Math Context */ - public FunctionSingle(MathContext mathContext) { + public FunctionSingle(final MathContext mathContext) { this.mathContext = mathContext; parameter = null; } /** * Create a new instance of FunctionSingle. - * + * * @param mathContext * Math Context * @param value * The parameter of this function. */ - public FunctionSingle(MathContext mathContext, Function value) { + public FunctionSingle(final MathContext mathContext, final Function value) { this.mathContext = mathContext; parameter = value; } @@ -53,7 +53,7 @@ public abstract class FunctionSingle implements Function { protected Function parameter; /** - * + * * @return Parameter. */ public Function getParameter() { @@ -61,33 +61,31 @@ public abstract class FunctionSingle implements Function { } /** - * + * * @param var * Parameter. * @return A new instance of this function. */ - public FunctionSingle setParameter(Function value) { + public FunctionSingle setParameter(final Function value) { final FunctionSingle s = clone(); s.parameter = value; return s; } @Override - public FunctionSingle setParameter(int index, Function var) throws IndexOutOfBoundsException { - if (index == 0) { + public FunctionSingle setParameter(final int index, final Function var) throws IndexOutOfBoundsException { + if (index == 0) return this.setParameter(var); - } else { + else throw new IndexOutOfBoundsException(); - } } @Override - public Function getParameter(int index) throws IndexOutOfBoundsException { - if (index == 0) { + public Function getParameter(final int index) throws IndexOutOfBoundsException { + if (index == 0) return this.getParameter(); - } else { + else throw new IndexOutOfBoundsException(); - } } @Override @@ -96,16 +94,14 @@ public abstract class FunctionSingle implements Function { } @Override - public final ObjectArrayList simplify(Rule rule) throws Error, InterruptedException { + public final ObjectArrayList simplify(final Rule rule) throws Error, InterruptedException { final ObjectArrayList simplifiedParam = parameter.simplify(rule); - if (simplifiedParam == null) { + if (simplifiedParam == null) return rule.execute(this); - } final ObjectArrayList result = new ObjectArrayList<>(); - for (final Function f : simplifiedParam) { + for (final Function f : simplifiedParam) result.add(this.setParameter(f)); - } return result; } diff --git a/core/src/main/java/it/cavallium/warppi/math/MathContext.java b/core/src/main/java/it/cavallium/warppi/math/MathContext.java index 46dce5cc..f3bb5711 100644 --- a/core/src/main/java/it/cavallium/warppi/math/MathContext.java +++ b/core/src/main/java/it/cavallium/warppi/math/MathContext.java @@ -24,7 +24,7 @@ public class MathContext { } @Deprecated - public Function parseString(String string) throws Error { + public Function parseString(final String string) throws Error { return null; /* if (string.contains("{")) { @@ -46,7 +46,7 @@ public class MathContext { } @Deprecated - public Function parseEquationString(String string) throws Error { + public Function parseEquationString(final String string) throws Error { return null; /* final String[] parts = string.split("="); @@ -60,7 +60,7 @@ public class MathContext { } @Deprecated - public ObjectArrayList solveExpression(ObjectArrayList input) throws Error { + public ObjectArrayList solveExpression(final ObjectArrayList input) throws Error { return null; /* ObjectArrayList results = new ObjectArrayList<>(); @@ -140,7 +140,7 @@ public class MathContext { throw new UnsupportedOperationException(); } - public ObjectArrayList getAcceptableRules(RuleType currentAcceptedRules) { + public ObjectArrayList getAcceptableRules(final RuleType currentAcceptedRules) { return RulesManager.rules[currentAcceptedRules.ordinal()]; } } diff --git a/core/src/main/java/it/cavallium/warppi/math/MathematicalSymbols.java b/core/src/main/java/it/cavallium/warppi/math/MathematicalSymbols.java index ce9fecce..40250e93 100644 --- a/core/src/main/java/it/cavallium/warppi/math/MathematicalSymbols.java +++ b/core/src/main/java/it/cavallium/warppi/math/MathematicalSymbols.java @@ -1,7 +1,5 @@ package it.cavallium.warppi.math; -import static it.cavallium.warppi.util.Utils.concat; - import it.cavallium.warppi.util.Utils; public class MathematicalSymbols { @@ -32,32 +30,31 @@ public class MathematicalSymbols { public static final char X = 'ⓧ'; public static final char Y = 'Ⓨ'; - public static final char[] functionsNSN = new char[] { NTH_ROOT, POWER }; + public static final char[] functionsNSN = new char[] { MathematicalSymbols.NTH_ROOT, MathematicalSymbols.POWER }; - public static final char[] functionsSN = new char[] { SQUARE_ROOT, POWER_OF_TWO, MINUS, SINE, COSINE, TANGENT, ARC_SINE, ARC_COSINE, ARC_TANGENT, LOGARITHM }; + public static final char[] functionsSN = new char[] { MathematicalSymbols.SQUARE_ROOT, MathematicalSymbols.POWER_OF_TWO, MathematicalSymbols.MINUS, MathematicalSymbols.SINE, MathematicalSymbols.COSINE, MathematicalSymbols.TANGENT, MathematicalSymbols.ARC_SINE, MathematicalSymbols.ARC_COSINE, MathematicalSymbols.ARC_TANGENT, MathematicalSymbols.LOGARITHM }; - public static final char[] functions = concat(functionsNSN, functionsSN); + public static final char[] functions = Utils.concat(MathematicalSymbols.functionsNSN, MathematicalSymbols.functionsSN); - private static final char[] signumsWithoutMultiplication = new char[] { SUM, SUM_SUBTRACTION, SUBTRACTION, DIVISION }; - private static final char[] signumsWithMultiplication = Utils.add(signumsWithoutMultiplication, MULTIPLICATION); + private static final char[] signumsWithoutMultiplication = new char[] { MathematicalSymbols.SUM, MathematicalSymbols.SUM_SUBTRACTION, MathematicalSymbols.SUBTRACTION, MathematicalSymbols.DIVISION }; + private static final char[] signumsWithMultiplication = Utils.add(MathematicalSymbols.signumsWithoutMultiplication, MathematicalSymbols.MULTIPLICATION); - public static final char[] functionsNSNAndSignums = concat(functionsNSN, signumsWithMultiplication); - public static final char[] functionsAndSignums = concat(functions, signumsWithMultiplication); + public static final char[] functionsNSNAndSignums = Utils.concat(MathematicalSymbols.functionsNSN, MathematicalSymbols.signumsWithMultiplication); + public static final char[] functionsAndSignums = Utils.concat(MathematicalSymbols.functions, MathematicalSymbols.signumsWithMultiplication); - public static final char[] signums(boolean withMultiplication) { - if (withMultiplication) { - return signumsWithMultiplication; - } - return signumsWithoutMultiplication; + public static final char[] signums(final boolean withMultiplication) { + if (withMultiplication) + return MathematicalSymbols.signumsWithMultiplication; + return MathematicalSymbols.signumsWithoutMultiplication; } - public static final char[] parentheses = new char[] { PARENTHESIS_OPEN, PARENTHESIS_CLOSE }; + public static final char[] parentheses = new char[] { MathematicalSymbols.PARENTHESIS_OPEN, MathematicalSymbols.PARENTHESIS_CLOSE }; - public static final char[] variables = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', X, Y, 'Z', PI, EULER_NUMBER, UNDEFINED }; + public static final char[] variables = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', MathematicalSymbols.X, MathematicalSymbols.Y, 'Z', MathematicalSymbols.PI, MathematicalSymbols.EULER_NUMBER, MathematicalSymbols.UNDEFINED }; - public static final char[] genericSyntax = new char[] { SYSTEM, EQUATION }; + public static final char[] genericSyntax = new char[] { MathematicalSymbols.SYSTEM, MathematicalSymbols.EQUATION }; - public static String getGraphicRepresentation(String string) { + public static String getGraphicRepresentation(final String string) { return string.replace("Ⓑ", "^").replace("Ⓒ", "SIN").replace("Ⓓ", "COS").replace("Ⓔ", "TAN").replace("Ⓕ", "ASIN").replace("Ⓖ", "ACOS").replace("Ⓗ", "ATAN"); } diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/Division.java b/core/src/main/java/it/cavallium/warppi/math/functions/Division.java index 3dd4a4bb..2b4c39e5 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/Division.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/Division.java @@ -11,12 +11,12 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class Division extends FunctionOperator { - public Division(MathContext root, Function value1, Function value2) { + public Division(final MathContext root, final Function value1, final Function value2) { super(root, value1, value2); } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { if (o instanceof Division) { final FunctionOperator f = (FunctionOperator) o; return getParameter1().equals(f.getParameter1()) && getParameter2().equals(f.getParameter2()); @@ -35,19 +35,17 @@ public class Division extends FunctionOperator { } @Override - public ObjectArrayList toBlock(MathContext context) throws Error { + public ObjectArrayList toBlock(final MathContext context) throws Error { final ObjectArrayList result = new ObjectArrayList<>(); final ObjectArrayList sub1 = getParameter1().toBlock(context); final ObjectArrayList sub2 = getParameter2().toBlock(context); final BlockDivision bd = new BlockDivision(); final BlockContainer uc = bd.getUpperContainer(); final BlockContainer lc = bd.getLowerContainer(); - for (final Block b : sub1) { + for (final Block b : sub1) uc.appendBlockUnsafe(b); - } - for (final Block b : sub2) { + for (final Block b : sub2) lc.appendBlockUnsafe(b); - } uc.recomputeDimensions(); lc.recomputeDimensions(); bd.recomputeDimensions(); diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/EmptyNumber.java b/core/src/main/java/it/cavallium/warppi/math/functions/EmptyNumber.java index b4cb287d..81577b4a 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/EmptyNumber.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/EmptyNumber.java @@ -9,14 +9,14 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class EmptyNumber implements Function { - public EmptyNumber(MathContext root) { + public EmptyNumber(final MathContext root) { this.root = root; } private final MathContext root; @Override - public ObjectArrayList simplify(Rule rule) throws Error, InterruptedException { + public ObjectArrayList simplify(final Rule rule) throws Error, InterruptedException { return rule.execute(this); } @@ -26,7 +26,7 @@ public class EmptyNumber implements Function { } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { return o instanceof EmptyNumber; } @@ -36,17 +36,17 @@ public class EmptyNumber implements Function { } @Override - public Function setParameter(int index, Function var) throws IndexOutOfBoundsException { + public Function setParameter(final int index, final Function var) throws IndexOutOfBoundsException { throw new IndexOutOfBoundsException(); } @Override - public Function getParameter(int index) throws IndexOutOfBoundsException { + public Function getParameter(final int index) throws IndexOutOfBoundsException { throw new IndexOutOfBoundsException(); } @Override - public ObjectArrayList toBlock(MathContext context) { + public ObjectArrayList toBlock(final MathContext context) { // TODO Auto-generated method stub return null; } diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/Expression.java b/core/src/main/java/it/cavallium/warppi/math/functions/Expression.java index 3f207eb7..5d57b627 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/Expression.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/Expression.java @@ -17,30 +17,30 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class Expression extends FunctionSingle { - public Expression(MathContext root) { + public Expression(final MathContext root) { super(root); } - public Expression(MathContext root, Function value) { + public Expression(final MathContext root, final Function value) { super(root, value); } private final boolean initialParenthesis = false; @Deprecated - public Expression(MathContext root, String string) throws Error { + public Expression(final MathContext root, final String string) throws Error { this(root, string, "", true); } @Deprecated - public Expression(MathContext root, String string, String debugSpaces, boolean initialParenthesis) throws Error { + public Expression(final MathContext root, final String string, final String debugSpaces, final boolean initialParenthesis) throws Error { super(root); /* super(root); this.initialParenthesis = initialParenthesis; boolean isNumber = false; - + // Determine if the expression is already a number: // Determina se l'espressione è già un numero: try { @@ -49,12 +49,12 @@ public class Expression extends FunctionSingle { } catch (final NumberFormatException ex) { isNumber = false; } - + String processExpression = string; Utils.debug.println(debugSpaces + "•Analyzing expression:" + processExpression); - + isNumber = false; //TODO: rimuovere isNumber, alcune semplificazione come la divisione per zero altrimenti verrebbero saltate. - + if (isNumber) { // If the expression is already a number: // Se l'espressione è già un numero: @@ -65,10 +65,10 @@ public class Expression extends FunctionSingle { // Else prepare the expression: // Altrimenti prepara l'espressione: debugSpaces += " "; - + // IF the expression is not a number: // Se l'espressione non è già un numero: - + // Check if there are more than one equal symbol (=) // Controlla se ci sono più di un uguale (=) int equationsFound = 0; @@ -88,7 +88,7 @@ public class Expression extends FunctionSingle { if (equationsFound != systemsFound) { throw new Error(Errors.SYNTAX_ERROR); } - + //Solve the exceeding symbols ++ and -- // Correggi i segni ++ e -- in eccesso Pattern pattern = Pattern.compile("\\+\\++?|\\-\\-+?"); @@ -100,7 +100,7 @@ public class Expression extends FunctionSingle { processExpression = processExpression.substring(0, matcher.start(0)) + correzione + processExpression.substring(matcher.start(0) + matcher.group(0).length(), processExpression.length()); matcher = pattern.matcher(processExpression); } - + // Correct the exceeding symbols +- and -+ // Correggi i segni +- e -+ in eccesso pattern = Pattern.compile("\\+\\-|\\-\\+"); @@ -111,25 +111,25 @@ public class Expression extends FunctionSingle { processExpression = processExpression.substring(0, matcher.start(0)) + correzione + processExpression.substring(matcher.start(0) + matcher.group(0).length(), processExpression.length()); matcher = pattern.matcher(processExpression); } - + // Rimuovi i segni appena dopo le parentesi if (processExpression.contains("(+")) { symbolsChanged = true; processExpression = processExpression.replace("(+", "("); } - + // // Cambia i segni appena prima le parentesi // if (processExpression.contains("-(")) { // symbolsChanged = true; // processExpression = processExpression.replace("-(", "-1*("); // } - + // Rimuovi i segni appena dopo l'inizio if (processExpression.startsWith("+")) { symbolsChanged = true; processExpression = processExpression.substring(1, processExpression.length()); } - + // Rimuovi i + in eccesso pattern = Pattern.compile("[" + ArrayToRegex(Utils.add(concat(MathematicalSymbols.signums(true), MathematicalSymbols.functions), '(')) + "]\\+[^" + ArrayToRegex(concat(concat(MathematicalSymbols.signums(true), MathematicalSymbols.functions), new char[] { '(', ')' })) + "]+?[" + ArrayToRegex(concat(MathematicalSymbols.signums(true), MathematicalSymbols.functions)) + "]|[" + ArrayToRegex(concat(MathematicalSymbols.signums(true), MathematicalSymbols.functions)) + "]+?\\+[^" + ArrayToRegex(concat(concat(MathematicalSymbols.signums(true), MathematicalSymbols.functions), new char[] { '(', ')' })) + "]"); matcher = pattern.matcher(processExpression); @@ -140,10 +140,10 @@ public class Expression extends FunctionSingle { processExpression = processExpression.substring(0, matcher.start(0) + 1) + correzione + processExpression.substring(matcher.start(0) + matcher.group(0).length(), processExpression.length()); matcher = pattern.matcher(processExpression); } - + // Correggi i segni - in − processExpression = processExpression.replace('-', MathematicalSymbols.SUBTRACTION); - + // Correggi i segni − dopo di espressioni o funzioni SN in - pattern = Pattern.compile("[" + Utils.ArrayToRegex(concat(concat(MathematicalSymbols.functions, new char[] { MathematicalSymbols.PARENTHESIS_OPEN }), MathematicalSymbols.signums(true))) + "]" + MathematicalSymbols.SUBTRACTION); matcher = pattern.matcher(processExpression); @@ -153,17 +153,17 @@ public class Expression extends FunctionSingle { processExpression = processExpression.substring(0, matcher.start(0) + 1) + correzione + processExpression.substring(matcher.start(0) + 2, processExpression.length()); matcher = pattern.matcher(processExpression); } - + // Cambia il segno iniziale − in - if (processExpression.startsWith("−")) { symbolsChanged = true; processExpression = "-" + processExpression.substring(1, processExpression.length()); } - + if (symbolsChanged) { Utils.debug.println(debugSpaces + "•Resolved signs:" + processExpression); } - + // // Aggiungi le parentesi implicite per le potenze con una incognita // pattern = Pattern.compile("(? oldFunctionsList = new ObjectArrayList<>(); for (int i = 0; i < oldFunctionsArray.length; i++) { @@ -423,10 +423,10 @@ public class Expression extends FunctionSingle { oldFunctionsList.add(funzione); } } - + if (oldFunctionsList.size() > 1) { Utils.debug.println(debugSpaces + " •Correcting classes:"); - + int before = 0; String step = "SN Functions"; int n = 0; @@ -457,18 +457,18 @@ public class Expression extends FunctionSingle { if (step != "SN Functions") { if ((step == "sums" && (funzioneTMP instanceof Sum || funzioneTMP instanceof SumSubtraction || funzioneTMP instanceof Subtraction) == true && ((funzioneTMP instanceof FunctionSingle && ((FunctionSingle) funzioneTMP).getParameter() == null) || (funzioneTMP instanceof FunctionOperator && ((FunctionOperator) funzioneTMP).getParameter1() == null && ((FunctionOperator) funzioneTMP).getParameter2() == null) || (!(funzioneTMP instanceof FunctionSingle) && !(funzioneTMP instanceof FunctionOperator)))) || (step.equals("multiplications") && ((funzioneTMP instanceof Multiplication) || (funzioneTMP instanceof Division)) && ((FunctionOperator) funzioneTMP).getParameter1() == null && ((FunctionOperator) funzioneTMP).getParameter2() == null) || (step == "NSN Functions" && (funzioneTMP instanceof Sum) == false && (funzioneTMP instanceof SumSubtraction) == false && (funzioneTMP instanceof Subtraction) == false && (funzioneTMP instanceof Multiplication) == false && (funzioneTMP instanceof Division) == false && ((funzioneTMP instanceof FunctionSingle && ((FunctionSingle) funzioneTMP).getParameter() == null) || (funzioneTMP instanceof FunctionOperator && ((FunctionOperator) funzioneTMP).getParameter1() == null && ((FunctionOperator) funzioneTMP).getParameter2() == null) || (!(funzioneTMP instanceof FunctionSingle) && !(funzioneTMP instanceof FunctionOperator))))) { change = true; - + if (i + 1 < oldFunctionsList.size() && i - 1 >= 0) { funzioneTMP = ((FunctionOperator) funzioneTMP).setParameter1(oldFunctionsList.get(i - 1)); funzioneTMP = ((FunctionOperator) funzioneTMP).setParameter2(oldFunctionsList.get(i + 1)); oldFunctionsList.set(i, funzioneTMP); - + // è importante togliere prima gli elementi // in fondo e poi quelli davanti, perché gli // indici scalano da destra a sinistra. oldFunctionsList.remove(i + 1); oldFunctionsList.remove(i - 1); - + Utils.debug.println(debugSpaces + " •Set variable to expression:" + funzioneTMP.getClass().getSimpleName()); try { Utils.debug.println(debugSpaces + " " + "var1=" + ((FunctionOperator) funzioneTMP).getParameter1().toString()); @@ -479,7 +479,7 @@ public class Expression extends FunctionSingle { try { Utils.debug.println(debugSpaces + " " + "(result)=" + ((FunctionOperator) funzioneTMP).toString()); } catch (final NullPointerException ex2) {} - + } else { throw new Error(Errors.SYNTAX_ERROR); } @@ -490,17 +490,17 @@ public class Expression extends FunctionSingle { if (i + 1 < oldFunctionsList.size()) { final Function nextFunc = oldFunctionsList.get(i + 1); if (nextFunc instanceof FunctionSingle && ((FunctionSingle) nextFunc).getParameter() == null) { - + } else { change = true; funzioneTMP = ((FunctionSingle) funzioneTMP).setParameter(nextFunc); oldFunctionsList.set(i, funzioneTMP); - + // è importante togliere prima gli elementi in // fondo e poi quelli davanti, perché gli indici // scalano da destra a sinistra. oldFunctionsList.remove(i + 1); - + Utils.debug.println(debugSpaces + " •Set variable to expression:" + funzioneTMP.getClass().getSimpleName()); final Function var = ((FunctionSingle) funzioneTMP).getParameter(); if (var == null) { @@ -531,14 +531,14 @@ public class Expression extends FunctionSingle { } else { super.functions = oldFunctionsList.toArray(new Function[oldFunctionsList.size()]); } - + dsl = debugSpaces.length(); debugSpaces = ""; for (int i = 0; i < dsl - 2; i++) { debugSpaces += " "; } Utils.debug.println(debugSpaces + "•Finished correcting classes."); - + final String result = toString(); Utils.debug.println(debugSpaces + "•Result:" + result); } @@ -547,35 +547,31 @@ public class Expression extends FunctionSingle { public boolean parenthesisNeeded() { boolean parenthesisneeded = true; - if (initialParenthesis) { + if (initialParenthesis) parenthesisneeded = false; - } else { + else { final Function f = getParameter(0); - if (f instanceof Number || f instanceof Variable || f instanceof Expression || f instanceof Division || f instanceof Joke || f instanceof Undefined || f instanceof Power || f instanceof Sine || f instanceof Cosine || f instanceof Tangent || f instanceof ArcSine || f instanceof ArcCosine || f instanceof ArcTangent || f instanceof RootSquare) { + if (f instanceof Number || f instanceof Variable || f instanceof Expression || f instanceof Division || f instanceof Joke || f instanceof Undefined || f instanceof Power || f instanceof Sine || f instanceof Cosine || f instanceof Tangent || f instanceof ArcSine || f instanceof ArcCosine || f instanceof ArcTangent || f instanceof RootSquare) parenthesisneeded = false; - } - if (f instanceof Multiplication) { - if (((Multiplication) f).getParameter1() instanceof Number) { + if (f instanceof Multiplication) + if (((Multiplication) f).getParameter1() instanceof Number) parenthesisneeded = !(((Multiplication) f).getParameter2() instanceof Variable); - } else if (((Multiplication) f).getParameter2() instanceof Number) { + else if (((Multiplication) f).getParameter2() instanceof Number) parenthesisneeded = !(((Multiplication) f).getParameter1() instanceof Variable); - } else if (((Multiplication) f).getParameter1() instanceof Variable || ((Multiplication) f).getParameter2() instanceof Variable) { + else if (((Multiplication) f).getParameter1() instanceof Variable || ((Multiplication) f).getParameter2() instanceof Variable) parenthesisneeded = false; - } - } } return parenthesisneeded; } @Override - public ObjectArrayList toBlock(MathContext context) throws Error { + public ObjectArrayList toBlock(final MathContext context) throws Error { final ObjectArrayList result = new ObjectArrayList<>(); final ObjectArrayList sub = getParameter(0).toBlock(context); final BlockParenthesis bp = new BlockParenthesis(); final BlockContainer bpc = bp.getNumberContainer(); - for (final Block b : sub) { + for (final Block b : sub) bpc.appendBlockUnsafe(b); - } bpc.recomputeDimensions(); bp.recomputeDimensions(); result.add(bp); @@ -585,26 +581,24 @@ public class Expression extends FunctionSingle { @Override public String toString() { String s = "("; - if (parameter == null) { + if (parameter == null) s += "null"; - } else { + else s += parameter.toString(); - } s += ")"; return s; } @Override - public boolean equals(Object o) { - if (parameter == null | o == null) { + public boolean equals(final Object o) { + if (parameter == null | o == null) return parameter == o; - } else { + else { final Function f = (Function) o; - if (f instanceof Expression) { - return (getParameter(0).equals(((Expression) f).getParameter(0))); - } else { - return (getParameter(0).equals(f)); - } + if (f instanceof Expression) + return getParameter(0).equals(((Expression) f).getParameter(0)); + else + return getParameter(0).equals(f); } } diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/Joke.java b/core/src/main/java/it/cavallium/warppi/math/functions/Joke.java index 0c9902fb..c3776f8d 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/Joke.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/Joke.java @@ -20,13 +20,13 @@ public class Joke implements Function { private final byte joke; private final MathContext root; - public Joke(MathContext root, byte joke) { + public Joke(final MathContext root, final byte joke) { this.root = root; this.joke = joke; } @Override - public ObjectArrayList simplify(Rule rule) throws Error, InterruptedException { + public ObjectArrayList simplify(final Rule rule) throws Error, InterruptedException { return rule.execute(this); } @@ -41,17 +41,17 @@ public class Joke implements Function { } @Override - public Function setParameter(int index, Function var) throws IndexOutOfBoundsException { + public Function setParameter(final int index, final Function var) throws IndexOutOfBoundsException { throw new IndexOutOfBoundsException(); } @Override - public Function getParameter(int index) throws IndexOutOfBoundsException { + public Function getParameter(final int index) throws IndexOutOfBoundsException { throw new IndexOutOfBoundsException(); } @Override - public ObjectArrayList toBlock(MathContext context) throws Error { + public ObjectArrayList toBlock(final MathContext context) throws Error { // TODO Auto-generated method stub throw new Error(Errors.NOT_IMPLEMENTED, "Unknown function " + getClass().getSimpleName()); } diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/Logarithm.java b/core/src/main/java/it/cavallium/warppi/math/functions/Logarithm.java index 4fa7ad78..5bb24e6d 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/Logarithm.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/Logarithm.java @@ -11,12 +11,12 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class Logarithm extends FunctionOperator { - public Logarithm(MathContext root, Function value1, Function value2) { + public Logarithm(final MathContext root, final Function value1, final Function value2) { super(root, value1, value2); } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { if (o instanceof Logarithm) { final FunctionOperator f = (FunctionOperator) o; return parameter1.equals(f.getParameter1()) && parameter2.equals(f.getParameter2()); @@ -30,19 +30,17 @@ public class Logarithm extends FunctionOperator { } @Override - public ObjectArrayList toBlock(MathContext context) throws Error { + public ObjectArrayList toBlock(final MathContext context) throws Error { final ObjectArrayList result = new ObjectArrayList<>(); final ObjectArrayList sub1 = getParameter1().toBlock(context); final ObjectArrayList sub2 = getParameter2().toBlock(context); final BlockLogarithm bd = new BlockLogarithm(); final BlockContainer uc = bd.getBaseContainer(); final BlockContainer lc = bd.getNumberContainer(); - for (final Block b : sub1) { + for (final Block b : sub1) uc.appendBlockUnsafe(b); - } - for (final Block b : sub2) { + for (final Block b : sub2) lc.appendBlockUnsafe(b); - } uc.recomputeDimensions(); lc.recomputeDimensions(); bd.recomputeDimensions(); diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/Multiplication.java b/core/src/main/java/it/cavallium/warppi/math/functions/Multiplication.java index 06b4f61c..59c5ccd4 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/Multiplication.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/Multiplication.java @@ -12,7 +12,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class Multiplication extends FunctionOperator { - public Multiplication(MathContext root, Function value1, Function value2) { + public Multiplication(final MathContext root, final Function value1, final Function value2) { super(root, value1, value2); /*if (value1 instanceof Variable && value2 instanceof Variable == false) { parameter1 = value2; @@ -21,14 +21,13 @@ public class Multiplication extends FunctionOperator { } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { if (o instanceof Multiplication) { final FunctionOperator f = (FunctionOperator) o; - if (parameter1.equals(f.getParameter1()) && parameter2.equals(f.getParameter2())) { + if (parameter1.equals(f.getParameter1()) && parameter2.equals(f.getParameter2())) return true; - } else if (parameter1.equals(f.getParameter2()) && parameter2.equals(f.getParameter1())) { + else if (parameter1.equals(f.getParameter2()) && parameter2.equals(f.getParameter1())) return true; - } } return false; } @@ -39,7 +38,7 @@ public class Multiplication extends FunctionOperator { } @Override - public ObjectArrayList toBlock(MathContext context) throws Error { + public ObjectArrayList toBlock(final MathContext context) throws Error { final ObjectArrayList result = new ObjectArrayList<>(); final Function par1 = getParameter1(); final Function par2 = getParameter2(); @@ -54,30 +53,26 @@ public class Multiplication extends FunctionOperator { final ObjectArrayList parBlocks = par2.toBlock(context); final BlockParenthesis par = new BlockParenthesis(parBlocks); result.add(par); - } else { + } else result.addAll(sub2); - } return result; } else { if (new Expression(context, par1).parenthesisNeeded()) { final ObjectArrayList parBlocks = par1.toBlock(context); final BlockParenthesis par = new BlockParenthesis(parBlocks); result.add(par); - } else { + } else result.addAll(sub1); - } - if ((nearLeft instanceof BlockChar && nearRight instanceof BlockChar) && !(par2 instanceof Negative) && !(par1 instanceof Number && par2 instanceof Number)) { + if (nearLeft instanceof BlockChar && nearRight instanceof BlockChar && !(par2 instanceof Negative) && !(par1 instanceof Number && par2 instanceof Number)) { - } else { + } else result.add(new BlockChar(MathematicalSymbols.MULTIPLICATION)); - } if (new Expression(context, par2).parenthesisNeeded()) { final ObjectArrayList parBlocks = par2.toBlock(context); final BlockParenthesis par = new BlockParenthesis(parBlocks); result.add(par); - } else { + } else result.addAll(sub2); - } return result; } } @@ -87,16 +82,15 @@ public class Multiplication extends FunctionOperator { } public Function toPositive() { - if (parameter1.equals(new Number(getMathContext(), -1))) { + if (parameter1.equals(new Number(getMathContext(), -1))) return parameter2; - } else if (parameter2.equals(new Number(getMathContext(), -1))) { + else if (parameter2.equals(new Number(getMathContext(), -1))) return parameter2; - } else { + else return null; - } } - public static Multiplication newNegative(MathContext context, Function value2) { + public static Multiplication newNegative(final MathContext context, final Function value2) { return new Multiplication(context, new Number(context, -1), value2); } } \ No newline at end of file diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/Negative.java b/core/src/main/java/it/cavallium/warppi/math/functions/Negative.java index 82d6bbee..b82850fb 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/Negative.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/Negative.java @@ -12,15 +12,14 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class Negative extends FunctionSingle { - public Negative(MathContext root, Function value) { + public Negative(final MathContext root, final Function value) { super(root, value); } @Override - public boolean equals(Object o) { - if (o instanceof Negative) { + public boolean equals(final Object o) { + if (o instanceof Negative) return ((Negative) o).getParameter().equals(parameter); - } return false; } @@ -30,20 +29,18 @@ public class Negative extends FunctionSingle { } @Override - public ObjectArrayList toBlock(MathContext context) throws Error { + public ObjectArrayList toBlock(final MathContext context) throws Error { final ObjectArrayList blocks = new ObjectArrayList<>(); blocks.add(new BlockChar(MathematicalSymbols.MINUS)); if (new Expression(context, getParameter()).parenthesisNeeded()) { final BlockParenthesis par = new BlockParenthesis(); final ObjectArrayList parBlocks = getParameter().toBlock(context); - for (final Block b : parBlocks) { + for (final Block b : parBlocks) par.getNumberContainer().appendBlockUnsafe(b); // Skips recomputeDimension - } par.recomputeDimensions(); // Recompute dimensions after appendBlockUnsafe blocks.add(par); - } else { + } else blocks.addAll(getParameter().toBlock(context)); - } return blocks; // throw new Error(Errors.NOT_IMPLEMENTED, "Unknown function " + getClass().getSimpleName()); } diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/Number.java b/core/src/main/java/it/cavallium/warppi/math/functions/Number.java index 3ee915e1..4632fbea 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/Number.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/Number.java @@ -23,29 +23,29 @@ public class Number implements Function { private final MathContext root; protected BigDecimal term; - public Number(MathContext root, BigInteger val) { + public Number(final MathContext root, final BigInteger val) { this.root = root; term = new BigDecimal(val).setScale(Utils.scale, Utils.scaleMode2); } - public Number(MathContext root, BigDecimal val) { + public Number(final MathContext root, final BigDecimal val) { this.root = root; term = val.setScale(Utils.scale, Utils.scaleMode2); } - public Number(MathContext root, String s) throws Error { + public Number(final MathContext root, final String s) throws Error { this(root, new BigDecimal(s).setScale(Utils.scale, Utils.scaleMode2)); } - public Number(MathContext root, int s) { + public Number(final MathContext root, final int s) { this(root, BigDecimal.valueOf(s).setScale(Utils.scale, Utils.scaleMode2)); } - public Number(MathContext root, float s) { + public Number(final MathContext root, final float s) { this(root, BigDecimal.valueOf(s).setScale(Utils.scale, Utils.scaleMode2)); } - public Number(MathContext root, double s) { + public Number(final MathContext root, final double s) { this(root, BigDecimal.valueOf(s).setScale(Utils.scale, Utils.scaleMode2)); } @@ -53,41 +53,38 @@ public class Number implements Function { return term; } - public void setTerm(BigDecimal val) { + public void setTerm(final BigDecimal val) { term = val.setScale(Utils.scale, Utils.scaleMode2); } - public Number add(Number f) { + public Number add(final Number f) { final Number ret = new Number(root, getTerm().add(f.getTerm())); return ret; } - public Number multiply(Number f) { + public Number multiply(final Number f) { final Number ret = new Number(root, getTerm().multiply(f.getTerm())); return ret; } - public Number divide(Number f) throws Error { + public Number divide(final Number f) throws Error { final Number ret = new Number(root, BigDecimalMath.divideRound(getTerm(), f.getTerm())); return ret; } - public Number pow(Number f) throws Error, InterruptedException { + public Number pow(final Number f) throws Error, InterruptedException { Number ret = new Number(root, BigDecimal.ONE); if (Utils.isIntegerValue(f.term)) { final BigInteger bi = f.term.toBigInteger().abs(); for (BigInteger i = BigInteger.ZERO; i.compareTo(bi) < 0; i = i.add(BigInteger.ONE)) { - if (Thread.interrupted()) { + if (Thread.interrupted()) throw new InterruptedException(); - } ret = ret.multiply(new Number(root, getTerm())); } - if (f.term.signum() == -1) { + if (f.term.signum() == -1) ret = new Number(root, 1).divide(ret); - } - } else { + } else ret.term = BigDecimalMath.pow(term, f.term); - } return ret; } @@ -99,15 +96,13 @@ public class Number implements Function { String s = sWith0.indexOf(".") < 0 ? sWith0 : sWith0.replaceAll("0*$", "").replaceAll("\\.$", ""); final String sExtended = sExtendedWith0.indexOf(".") < 0 ? sExtendedWith0 : sExtendedWith0.replaceAll("0*$", "").replaceAll("\\.$", ""); - if (sExtended.length() > s.length()) { + if (sExtended.length() > s.length()) s = s + "…"; - } if (root.exactMode == false) { final String cuttedNumber = s.split("\\.")[0]; - if (cuttedNumber.length() > 8) { + if (cuttedNumber.length() > 8) return cuttedNumber.substring(0, 1) + "," + cuttedNumber.substring(1, 8) + "ℯ℮" + (cuttedNumber.length() - 1); - } } return s; } @@ -118,7 +113,7 @@ public class Number implements Function { } @Override - public ObjectArrayList simplify(Rule rule) throws Error, InterruptedException { + public ObjectArrayList simplify(final Rule rule) throws Error, InterruptedException { return rule.execute(this); } @@ -136,22 +131,19 @@ public class Number implements Function { } @Override - public boolean equals(Object o) { - if (o != null & term != null) { + public boolean equals(final Object o) { + if (o != null & term != null) if (o instanceof Number) { final BigDecimal nav = ((Number) o).getTerm(); final boolean na1 = term.compareTo(BigDecimal.ZERO) == 0; final boolean na2 = nav.compareTo(BigDecimal.ZERO) == 0; if (na1 == na2) { - if (na1 == true) { + if (na1 == true) return true; - } - } else { + } else return false; - } return nav.compareTo(term) == 0; } - } return false; } @@ -164,12 +156,12 @@ public class Number implements Function { * @Override * public void draw(int x, int y, Graphics g) { * } - * + * * @Override * public int getHeight() { * return Utils.getFontHeight(); * } - * + * * @Override * public int getWidth() { * return 6*toString().length()-1; @@ -177,9 +169,8 @@ public class Number implements Function { */ public boolean canBeFactorized() { - if (Utils.isIntegerValue(getTerm())) { + if (Utils.isIntegerValue(getTerm())) return getTerm().toBigIntegerExact().compareTo(BigInteger.valueOf(1)) > 1; - } return false; } @@ -195,21 +186,18 @@ public class Number implements Function { final int comparedToZero = n.compareTo(zero); final int comparedToTwo = n.compareTo(two); - if (comparedToZero == 0) { + if (comparedToZero == 0) return fs; - } - if (comparedToTwo < 0) { - if (comparedToZero > 0) { + if (comparedToTwo < 0) + if (comparedToZero > 0) return fs; - } else { + else { fs.add(BigInteger.valueOf(-1)); n = n.multiply(BigInteger.valueOf(-1)); } - } - if (n.compareTo(two) < 0) { + if (n.compareTo(two) < 0) throw new IllegalArgumentException("must be greater than one"); - } while (n.mod(two).equals(BigInteger.ZERO)) { fs.add(two); @@ -218,14 +206,12 @@ public class Number implements Function { if (n.compareTo(BigInteger.ONE) > 0) { BigInteger f = BigInteger.valueOf(3); - while (f.compareTo(Utils.maxFactor) <= 0 && f.multiply(f).compareTo(n) <= 0) { + while (f.compareTo(Utils.maxFactor) <= 0 && f.multiply(f).compareTo(n) <= 0) if (n.mod(f).equals(BigInteger.ZERO)) { fs.add(f); n = n.divide(f); - } else { + } else f = f.add(two); - } - } fs.add(n); } @@ -233,38 +219,34 @@ public class Number implements Function { } @Override - public ObjectArrayList toBlock(MathContext context) { + public ObjectArrayList toBlock(final MathContext context) { final ObjectArrayList result = new ObjectArrayList<>(); final String numberString = toString(); if (numberString.contains("ℯ℮")) { final String[] numberParts = numberString.split("ℯ℮", 2); final BlockPower bp = new BlockExponentialNotation(); final BlockContainer bpec = bp.getExponentContainer(); - for (final char c : numberParts[0].toCharArray()) { + for (final char c : numberParts[0].toCharArray()) result.add(new BlockChar(c)); - } - for (final char c : numberParts[1].toCharArray()) { - bpec.appendBlockUnsafe(new BlockChar(c)); - } ; + for (final char c : numberParts[1].toCharArray()) + bpec.appendBlockUnsafe(new BlockChar(c));; bpec.recomputeDimensions(); bp.recomputeDimensions(); result.add(bp); return result; - } else { - for (final char c : numberString.toCharArray()) { + } else + for (final char c : numberString.toCharArray()) result.add(new BlockChar(c)); - } - } return result; } @Override - public Function setParameter(int index, Function var) throws IndexOutOfBoundsException { + public Function setParameter(final int index, final Function var) throws IndexOutOfBoundsException { throw new IndexOutOfBoundsException(); } @Override - public Function getParameter(int index) throws IndexOutOfBoundsException { + public Function getParameter(final int index) throws IndexOutOfBoundsException { throw new IndexOutOfBoundsException(); } } diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/Power.java b/core/src/main/java/it/cavallium/warppi/math/functions/Power.java index 44d93f26..ac7419fd 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/Power.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/Power.java @@ -11,12 +11,12 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class Power extends FunctionOperator { - public Power(MathContext root, Function value1, Function value2) { + public Power(final MathContext root, final Function value1, final Function value2) { super(root, value1, value2); } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { if (o instanceof Power) { final FunctionOperator f = (FunctionOperator) o; return parameter1.equals(f.getParameter1()) && parameter2.equals(f.getParameter2()); @@ -30,16 +30,15 @@ public class Power extends FunctionOperator { } @Override - public ObjectArrayList toBlock(MathContext context) throws Error { + public ObjectArrayList toBlock(final MathContext context) throws Error { final ObjectArrayList result = new ObjectArrayList<>(); final ObjectArrayList sub1 = getParameter1().toBlock(context); final ObjectArrayList sub2 = getParameter2().toBlock(context); final BlockPower bp = new BlockPower(); final BlockContainer ec = bp.getExponentContainer(); result.addAll(sub1); - for (final Block b : sub2) { + for (final Block b : sub2) ec.appendBlockUnsafe(b); - } ec.recomputeDimensions(); bp.recomputeDimensions(); result.add(bp); diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/Root.java b/core/src/main/java/it/cavallium/warppi/math/functions/Root.java index 57eb48a1..47647ccb 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/Root.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/Root.java @@ -10,12 +10,12 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class Root extends FunctionOperator { - public Root(MathContext root, Function value1, Function value2) { + public Root(final MathContext root, final Function value1, final Function value2) { super(root, value1, value2); } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { if (o instanceof Root) { final FunctionOperator f = (FunctionOperator) o; return parameter1.equals(f.getParameter1()) && parameter2.equals(f.getParameter2()); @@ -29,7 +29,7 @@ public class Root extends FunctionOperator { } @Override - public ObjectArrayList toBlock(MathContext context) throws Error { + public ObjectArrayList toBlock(final MathContext context) throws Error { // TODO Auto-generated method stub throw new Error(Errors.NOT_IMPLEMENTED, "Unknown function " + getClass().getSimpleName()); } diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/RootSquare.java b/core/src/main/java/it/cavallium/warppi/math/functions/RootSquare.java index 278c0370..f51d2682 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/RootSquare.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/RootSquare.java @@ -11,12 +11,12 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class RootSquare extends FunctionOperator { - public RootSquare(MathContext root, Function value2) { + public RootSquare(final MathContext root, final Function value2) { super(root, new Number(root, 2), value2); } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { if (o instanceof Root) { final FunctionOperator f = (FunctionOperator) o; return parameter1.equals(f.getParameter1()) && parameter2.equals(f.getParameter2()); @@ -30,16 +30,15 @@ public class RootSquare extends FunctionOperator { } @Override - public ObjectArrayList toBlock(MathContext context) throws Error { + public ObjectArrayList toBlock(final MathContext context) throws Error { final ObjectArrayList result = new ObjectArrayList<>(); final BlockSquareRoot bsqr = new BlockSquareRoot(); final BlockContainer bsqrc = bsqr.getNumberContainer(); - for (final Block b : getParameter2().toBlock(context)) { + for (final Block b : getParameter2().toBlock(context)) bsqrc.appendBlockUnsafe(b); - } bsqrc.recomputeDimensions(); bsqr.recomputeDimensions(); - result.add((bsqr)); + result.add(bsqr); return result; } diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/Subtraction.java b/core/src/main/java/it/cavallium/warppi/math/functions/Subtraction.java index 5717eb2b..9ea9707b 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/Subtraction.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/Subtraction.java @@ -11,12 +11,12 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class Subtraction extends FunctionOperator { - public Subtraction(MathContext root, Function value1, Function value2) { + public Subtraction(final MathContext root, final Function value1, final Function value2) { super(root, value1, value2); } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { if (o instanceof Subtraction) { final FunctionOperator f = (FunctionOperator) o; return parameter1.equals(f.getParameter1()) && parameter2.equals(f.getParameter2()); @@ -30,7 +30,7 @@ public class Subtraction extends FunctionOperator { } @Override - public ObjectArrayList toBlock(MathContext context) throws Error { + public ObjectArrayList toBlock(final MathContext context) throws Error { final ObjectArrayList result = new ObjectArrayList<>(); result.addAll(getParameter1().toBlock(context)); result.add(new BlockChar(MathematicalSymbols.SUBTRACTION)); diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/Sum.java b/core/src/main/java/it/cavallium/warppi/math/functions/Sum.java index ab3d020d..b5e827d4 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/Sum.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/Sum.java @@ -11,19 +11,18 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class Sum extends FunctionOperator { - public Sum(MathContext root, Function value1, Function value2) { + public Sum(final MathContext root, final Function value1, final Function value2) { super(root, value1, value2); } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { if (o instanceof Sum) { final FunctionOperator f = (FunctionOperator) o; - if (parameter1.equals(f.getParameter1()) && parameter2.equals(f.getParameter2())) { + if (parameter1.equals(f.getParameter1()) && parameter2.equals(f.getParameter2())) return true; - } else if (parameter1.equals(f.getParameter2()) && parameter2.equals(f.getParameter1())) { + else if (parameter1.equals(f.getParameter2()) && parameter2.equals(f.getParameter1())) return true; - } } return false; } @@ -34,7 +33,7 @@ public class Sum extends FunctionOperator { } @Override - public ObjectArrayList toBlock(MathContext context) throws Error { + public ObjectArrayList toBlock(final MathContext context) throws Error { final ObjectArrayList result = new ObjectArrayList<>(); result.addAll(getParameter1().toBlock(context)); result.add(new BlockChar(MathematicalSymbols.SUM)); diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/SumSubtraction.java b/core/src/main/java/it/cavallium/warppi/math/functions/SumSubtraction.java index d25418b5..bcf54b12 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/SumSubtraction.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/SumSubtraction.java @@ -11,12 +11,12 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class SumSubtraction extends FunctionOperator { - public SumSubtraction(MathContext root, Function value1, Function value2) { + public SumSubtraction(final MathContext root, final Function value1, final Function value2) { super(root, value1, value2); } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { if (o instanceof SumSubtraction) { final FunctionOperator f = (FunctionOperator) o; return parameter1.equals(f.getParameter1()) && parameter2.equals(f.getParameter2()); @@ -30,7 +30,7 @@ public class SumSubtraction extends FunctionOperator { } @Override - public ObjectArrayList toBlock(MathContext context) throws Error { + public ObjectArrayList toBlock(final MathContext context) throws Error { final ObjectArrayList result = new ObjectArrayList<>(); result.addAll(getParameter1().toBlock(context)); result.add(new BlockChar(MathematicalSymbols.SUM_SUBTRACTION)); diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/Undefined.java b/core/src/main/java/it/cavallium/warppi/math/functions/Undefined.java index 6286db18..23b5477b 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/Undefined.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/Undefined.java @@ -12,12 +12,12 @@ public class Undefined implements Function { protected final MathContext root; - public Undefined(MathContext root) { + public Undefined(final MathContext root) { this.root = root; } @Override - public ObjectArrayList simplify(Rule rule) throws Error, InterruptedException { + public ObjectArrayList simplify(final Rule rule) throws Error, InterruptedException { return rule.execute(this); } @@ -27,7 +27,7 @@ public class Undefined implements Function { } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { return false; } @@ -37,17 +37,17 @@ public class Undefined implements Function { } @Override - public Function setParameter(int index, Function var) throws IndexOutOfBoundsException { + public Function setParameter(final int index, final Function var) throws IndexOutOfBoundsException { throw new IndexOutOfBoundsException(); } @Override - public Function getParameter(int index) throws IndexOutOfBoundsException { + public Function getParameter(final int index) throws IndexOutOfBoundsException { throw new IndexOutOfBoundsException(); } @Override - public ObjectArrayList toBlock(MathContext context) { + public ObjectArrayList toBlock(final MathContext context) { final ObjectArrayList result = new ObjectArrayList<>(); result.add(new BlockUndefined()); return result; diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/Variable.java b/core/src/main/java/it/cavallium/warppi/math/functions/Variable.java index 4e8fe1b9..b6d98665 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/Variable.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/Variable.java @@ -14,13 +14,13 @@ public class Variable implements Function { protected final MathContext root; protected V_TYPE type = V_TYPE.CONSTANT; - public Variable(MathContext root, char val, V_TYPE type) { + public Variable(final MathContext root, final char val, final V_TYPE type) { this.root = root; var = val; this.type = type; } - public Variable(MathContext root, String s, V_TYPE type) throws Error { + public Variable(final MathContext root, final String s, final V_TYPE type) throws Error { this(root, s.charAt(0), type); } @@ -28,7 +28,7 @@ public class Variable implements Function { return var; } - public Variable setChar(char val) { + public Variable setChar(final char val) { return new Variable(root, val, type); } @@ -36,7 +36,7 @@ public class Variable implements Function { return type; } - public Variable setType(V_TYPE typ) { + public Variable setType(final V_TYPE typ) { return new Variable(root, var, typ); } @@ -49,14 +49,14 @@ public class Variable implements Function { public final Variable v; public final Number n; - public VariableValue(Variable v, Number n) { + public VariableValue(final Variable v, final Number n) { this.v = v; this.n = n; } } @Override - public ObjectArrayList simplify(Rule rule) throws Error, InterruptedException { + public ObjectArrayList simplify(final Rule rule) throws Error, InterruptedException { return rule.execute(this); } @@ -66,10 +66,9 @@ public class Variable implements Function { } @Override - public boolean equals(Object o) { - if (o instanceof Variable) { + public boolean equals(final Object o) { + if (o instanceof Variable) return ((Variable) o).getChar() == var && ((Variable) o).getType() == type; - } return false; } @@ -88,17 +87,17 @@ public class Variable implements Function { } @Override - public Function setParameter(int index, Function var) throws IndexOutOfBoundsException { + public Function setParameter(final int index, final Function var) throws IndexOutOfBoundsException { throw new IndexOutOfBoundsException(); } @Override - public Function getParameter(int index) throws IndexOutOfBoundsException { + public Function getParameter(final int index) throws IndexOutOfBoundsException { throw new IndexOutOfBoundsException(); } @Override - public ObjectArrayList toBlock(MathContext context) { + public ObjectArrayList toBlock(final MathContext context) { final ObjectArrayList result = new ObjectArrayList<>(); //TODO: Temporary solution. In near future Variables will be distint objects and they will have a color. So they will be no longer a BlockChar/FeatureChar result.add(new BlockChar(getChar())); diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/equations/Equation.java b/core/src/main/java/it/cavallium/warppi/math/functions/equations/Equation.java index df6ce4da..e30b60d5 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/equations/Equation.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/equations/Equation.java @@ -14,11 +14,11 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class Equation extends FunctionOperator { - public Equation(MathContext root, Function value1, Function value2) { + public Equation(final MathContext root, final Function value1, final Function value2) { super(root, value1, value2); } - public List solve(char variableCharacter) { + public List solve(final char variableCharacter) { @SuppressWarnings("unused") final ObjectArrayList e; //TODO: WORK IN PROGRESS. @@ -27,15 +27,14 @@ public class Equation extends FunctionOperator { } //WORK IN PROGRESS - public ObjectArrayList solveStep(char charIncognita) { + public ObjectArrayList solveStep(final char charIncognita) { ObjectArrayList result = new ObjectArrayList<>(); result.add(clone()); for (final SolveMethod t : SolveMethod.techniques) { final ObjectArrayList newResults = new ObjectArrayList<>(); final int sz = result.size(); - for (int n = 0; n < sz; n++) { + for (int n = 0; n < sz; n++) newResults.addAll(t.solve(result.get(n))); - } final Set hs = new HashSet<>(); hs.addAll(newResults); newResults.clear(); @@ -52,13 +51,13 @@ public class Equation extends FunctionOperator { } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { // TODO Auto-generated method stub return false; } @Override - public ObjectArrayList toBlock(MathContext context) throws Error { + public ObjectArrayList toBlock(final MathContext context) throws Error { // TODO Auto-generated method stub return null; } diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/equations/EquationResult.java b/core/src/main/java/it/cavallium/warppi/math/functions/equations/EquationResult.java index ccd80dc7..8ec671a4 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/equations/EquationResult.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/equations/EquationResult.java @@ -6,7 +6,7 @@ public class EquationResult { public boolean isAnEquation = false; public Number LR; - public EquationResult(Number LR, boolean isAnEquation) { + public EquationResult(final Number LR, final boolean isAnEquation) { this.LR = LR; this.isAnEquation = isAnEquation; } diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/equations/EquationsSystem.java b/core/src/main/java/it/cavallium/warppi/math/functions/equations/EquationsSystem.java index d1447c9a..6c50a3b8 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/equations/EquationsSystem.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/equations/EquationsSystem.java @@ -10,15 +10,15 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class EquationsSystem extends FunctionDynamic { static final int spacing = 2; - public EquationsSystem(MathContext root) { + public EquationsSystem(final MathContext root) { super(root); } - public EquationsSystem(MathContext root, Function value) { + public EquationsSystem(final MathContext root, final Function value) { super(root, new Function[] { value }); } - public EquationsSystem(MathContext root, Function[] value) { + public EquationsSystem(final MathContext root, final Function[] value) { super(root, value); } @@ -28,7 +28,7 @@ public class EquationsSystem extends FunctionDynamic { } @Override - public ObjectArrayList toBlock(MathContext context) throws Error { + public ObjectArrayList toBlock(final MathContext context) throws Error { // TODO Auto-generated method stub return null; } diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/equations/EquationsSystemPart.java b/core/src/main/java/it/cavallium/warppi/math/functions/equations/EquationsSystemPart.java index 01eed2e9..c6c0da45 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/equations/EquationsSystemPart.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/equations/EquationsSystemPart.java @@ -8,12 +8,12 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class EquationsSystemPart extends FunctionSingle { - public EquationsSystemPart(MathContext root, Equation equazione) { + public EquationsSystemPart(final MathContext root, final Equation equazione) { super(root, equazione); } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { // TODO Auto-generated method stub return false; } @@ -24,7 +24,7 @@ public class EquationsSystemPart extends FunctionSingle { } @Override - public ObjectArrayList toBlock(MathContext context) throws Error { + public ObjectArrayList toBlock(final MathContext context) throws Error { // TODO Auto-generated method stub return null; } diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/ArcCosine.java b/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/ArcCosine.java index 82e993aa..5aee0115 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/ArcCosine.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/ArcCosine.java @@ -10,12 +10,12 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class ArcCosine extends FunctionSingle { - public ArcCosine(MathContext root, Function value) { + public ArcCosine(final MathContext root, final Function value) { super(root, value); } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { // TODO Auto-generated method stub return false; } @@ -27,7 +27,7 @@ public class ArcCosine extends FunctionSingle { } @Override - public ObjectArrayList toBlock(MathContext context) throws Error { + public ObjectArrayList toBlock(final MathContext context) throws Error { // TODO Auto-generated method stub throw new Error(Errors.NOT_IMPLEMENTED, "Unknown function " + getClass().getSimpleName()); } diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/ArcSine.java b/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/ArcSine.java index 438c5fb4..166a81e0 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/ArcSine.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/ArcSine.java @@ -10,12 +10,12 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class ArcSine extends FunctionSingle { - public ArcSine(MathContext root, Function value) { + public ArcSine(final MathContext root, final Function value) { super(root, value); } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { // TODO Auto-generated method stub return false; } @@ -27,7 +27,7 @@ public class ArcSine extends FunctionSingle { } @Override - public ObjectArrayList toBlock(MathContext context) throws Error { + public ObjectArrayList toBlock(final MathContext context) throws Error { // TODO Auto-generated method stub throw new Error(Errors.NOT_IMPLEMENTED, "Unknown function " + getClass().getSimpleName()); } diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/ArcTangent.java b/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/ArcTangent.java index bd722c85..e3387e74 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/ArcTangent.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/ArcTangent.java @@ -10,12 +10,12 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class ArcTangent extends FunctionSingle { - public ArcTangent(MathContext root, Function value) { + public ArcTangent(final MathContext root, final Function value) { super(root, value); } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { // TODO Auto-generated method stub return false; } @@ -27,7 +27,7 @@ public class ArcTangent extends FunctionSingle { } @Override - public ObjectArrayList toBlock(MathContext context) throws Error { + public ObjectArrayList toBlock(final MathContext context) throws Error { // TODO Auto-generated method stub throw new Error(Errors.NOT_IMPLEMENTED, "Unknown function " + getClass().getSimpleName()); } diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/Cosine.java b/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/Cosine.java index 53efc680..4a160fc5 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/Cosine.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/Cosine.java @@ -10,12 +10,12 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class Cosine extends FunctionSingle { - public Cosine(MathContext root, Function value) { + public Cosine(final MathContext root, final Function value) { super(root, value); } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { // TODO Auto-generated method stub return false; } @@ -27,7 +27,7 @@ public class Cosine extends FunctionSingle { } @Override - public ObjectArrayList toBlock(MathContext context) throws Error { + public ObjectArrayList toBlock(final MathContext context) throws Error { // TODO Auto-generated method stub throw new Error(Errors.NOT_IMPLEMENTED, "Unknown function " + getClass().getSimpleName()); } diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/Sine.java b/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/Sine.java index 65c1a4bf..3d745a10 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/Sine.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/Sine.java @@ -11,17 +11,16 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class Sine extends FunctionSingle { - public Sine(MathContext root, Function value) { + public Sine(final MathContext root, final Function value) { super(root, value); } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { if (o instanceof Sine) { final FunctionSingle f = (FunctionSingle) o; - if (parameter.equals(f.getParameter())) { + if (parameter.equals(f.getParameter())) return true; - } } return false; } @@ -32,14 +31,13 @@ public class Sine extends FunctionSingle { } @Override - public ObjectArrayList toBlock(MathContext context) throws Error { + public ObjectArrayList toBlock(final MathContext context) throws Error { final ObjectArrayList result = new ObjectArrayList<>(); final ObjectArrayList sub = getParameter(0).toBlock(context); final BlockSine bs = new BlockSine(); final BlockContainer bpc = bs.getNumberContainer(); - for (final Block b : sub) { + for (final Block b : sub) bpc.appendBlockUnsafe(b); - } bpc.recomputeDimensions(); bs.recomputeDimensions(); result.add(bs); diff --git a/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/Tangent.java b/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/Tangent.java index 0693a2b7..100cffee 100644 --- a/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/Tangent.java +++ b/core/src/main/java/it/cavallium/warppi/math/functions/trigonometry/Tangent.java @@ -9,12 +9,12 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class Tangent extends FunctionSingle { - public Tangent(MathContext root, Function value) { + public Tangent(final MathContext root, final Function value) { super(root, value); } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { // TODO Auto-generated method stub return false; } @@ -26,7 +26,7 @@ public class Tangent extends FunctionSingle { } @Override - public ObjectArrayList toBlock(MathContext context) throws Error { + public ObjectArrayList toBlock(final MathContext context) throws Error { // TODO Auto-generated method stub return null; } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/MathParser.java b/core/src/main/java/it/cavallium/warppi/math/parser/MathParser.java index 43243704..1d3aec57 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/MathParser.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/MathParser.java @@ -32,7 +32,7 @@ import it.cavallium.warppi.util.IntWrapper; import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class MathParser { - public static Expression parseInput(MathContext context, InputContainer c) throws Error { + public static Expression parseInput(final MathContext context, final InputContainer c) throws Error { Expression result; final Function resultFunction = c.toFunction(context); @@ -41,14 +41,13 @@ public class MathParser { return result; } - public static ObjectArrayList> parseOutput(MathContext context, - ObjectArrayList resultExpressions) throws Error { + public static ObjectArrayList> parseOutput(final MathContext context, + final ObjectArrayList resultExpressions) throws Error { final ObjectArrayList> result = new ObjectArrayList<>(); for (final Function resultExpression : resultExpressions) { final ObjectArrayList resultBlocks = resultExpression.toBlock(context); - if (resultBlocks == null) { + if (resultBlocks == null) throw new Error(Errors.NOT_IMPLEMENTED, "Unknown function " + resultExpression.getClass().getSimpleName()); - } result.add(resultBlocks); } return result; @@ -56,45 +55,41 @@ public class MathParser { public static Function joinFeatures(final MathContext context, ObjectArrayList features) throws Error { - features = fixFeatures(context, features); + features = MathParser.fixFeatures(context, features); ObjectArrayList process = new ObjectArrayList<>(); for (final Feature f : features) { final Function fnc = f.toFunction(context); - if (fnc == null) { + if (fnc == null) throw new Error(Errors.SYNTAX_ERROR, "\"" + f.getClass().getSimpleName() + "\" can't be converted into a Function!"); - } process.add(fnc); } - process = fixStack(context, process); + process = MathParser.fixStack(context, process); - if (process.size() > 1) { + if (process.size() > 1) throw new Error(Errors.UNBALANCED_STACK, "The stack is unbalanced. Not all the functions are nested correctly"); - } return process.get(0); } - private static ObjectArrayList fixStack(MathContext context, ObjectArrayList functionsList) - throws Error { + private static ObjectArrayList fixStack(final MathContext context, + final ObjectArrayList functionsList) throws Error { final MathParserStep[] steps = new MathParserStep[] { new JoinNumberAndVariables(context), new FixSingleFunctionArgs(), new RemoveParentheses(context), new FixMultiplicationsAndDivisions(), new FixSumsAndSubtractions(), new AddImplicitMultiplications(context), }; boolean lastLoopDidSomething; Function lastElement; if (Engine.getPlatform().getSettings().isDebugEnabled()) { Engine.getPlatform().getConsoleUtils().out().print(ConsoleUtils.OUTPUTLEVEL_DEBUG_VERBOSE, "\tStatus: "); - for (final Function f : functionsList) { + for (final Function f : functionsList) Engine.getPlatform().getConsoleUtils().out().print(ConsoleUtils.OUTPUTLEVEL_DEBUG_VERBOSE, f.toString()); - } Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_VERBOSE); } for (final MathParserStep step : steps) { - if (Engine.getPlatform().getSettings().isDebugEnabled()) { + if (Engine.getPlatform().getSettings().isDebugEnabled()) Engine.getPlatform().getConsoleUtils().out().println(2, "Stack fixing step \"" + step.getStepName() + "\""); - } final int stepQty = step.requiresReversedIteration() ? -1 : 1, initialIndex = step.requiresReversedIteration() ? functionsList.size() - 1 : 0; do { @@ -105,20 +100,18 @@ public class MathParser { final int i = curIndex.i; final Function f = functionsList.get(i); - if (step.eval(curIndex, lastElement, f, functionsList)) { + if (step.eval(curIndex, lastElement, f, functionsList)) lastLoopDidSomething = true; - } - lastElement = (i >= functionsList.size()) ? null : functionsList.get(i); + lastElement = i >= functionsList.size() ? null : functionsList.get(i); curIndex.i += stepQty; } } while (lastLoopDidSomething); if (Engine.getPlatform().getSettings().isDebugEnabled()) { Engine.getPlatform().getConsoleUtils().out().print(ConsoleUtils.OUTPUTLEVEL_DEBUG_VERBOSE, "\tStatus: "); - for (final Function f : functionsList) { + for (final Function f : functionsList) Engine.getPlatform().getConsoleUtils().out().print(ConsoleUtils.OUTPUTLEVEL_DEBUG_VERBOSE, f.toString()); - } Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_VERBOSE); } } @@ -142,29 +135,29 @@ public class MathParser { private static ObjectArrayList fixFeatures(final MathContext context, ObjectArrayList features) throws Error { - features = fixMinuses(context, features); + features = MathParser.fixMinuses(context, features); - features = makeNumbers(context, features); + features = MathParser.makeNumbers(context, features); - features = makePowers(context, features); + features = MathParser.makePowers(context, features); - features = convertFunctionChars(context, features); + features = MathParser.convertFunctionChars(context, features); return features; } /** * Create function features from char features - * + * * @param context * @param features * @return */ - private static ObjectArrayList convertFunctionChars(MathContext context, ObjectArrayList features) - throws Error { + private static ObjectArrayList convertFunctionChars(final MathContext context, + final ObjectArrayList features) throws Error { final ObjectArrayList process = new ObjectArrayList<>(); - for (final Feature f : features) { + for (final Feature f : features) if (f instanceof FeatureChar) { final char featureChar = ((FeatureChar) f).ch; Feature result = null; @@ -186,107 +179,95 @@ public class MathParser { break; } - for (final char var : MathematicalSymbols.variables) { + for (final char var : MathematicalSymbols.variables) if (featureChar == var) { result = new FeatureVariable(featureChar, V_TYPE.VARIABLE); break; } - } - if (result == null) { + if (result == null) throw new Error(Errors.SYNTAX_ERROR, "Char " + featureChar + " isn't a known feature"); - } process.add(result); - } else { + } else process.add(f); - } - } return process; } /** * Make numbers [-][1][2][+][-][3] => [-12] - * + * * @param context * @param features * @return */ - private static ObjectArrayList makeNumbers(MathContext context, ObjectArrayList features) { + private static ObjectArrayList makeNumbers(final MathContext context, + final ObjectArrayList features) { final ObjectArrayList process = new ObjectArrayList<>(); FeatureNumber numberBuffer = null; - for (final Feature f : features) { + for (final Feature f : features) if (f instanceof FeatureChar) { final FeatureChar bcf = (FeatureChar) f; final char[] numbers = MathematicalSymbols.numbers; boolean isNumber = false; - for (final char n : numbers) { + for (final char n : numbers) if (bcf.ch == n) { isNumber = true; break; } - } - if (bcf.ch == MathematicalSymbols.MINUS || bcf.ch == '.') { + if (bcf.ch == MathematicalSymbols.MINUS || bcf.ch == '.') isNumber = true; - } if (isNumber) { if (numberBuffer == null) { numberBuffer = new FeatureNumber(bcf.ch); process.add(numberBuffer); - } else { + } else numberBuffer.append(bcf.ch); - } } else { - if (numberBuffer != null) { + if (numberBuffer != null) numberBuffer = null; - } process.add(f); } - } else { + } else process.add(f); - } - } return process; } /** * Fix minuses [-][1][2][+][-][3][-][2] => [-][12][+][-][3][—][2] - * + * * @param context * @param features * @return * @throws Error */ - private static ObjectArrayList fixMinuses(final MathContext context, ObjectArrayList features) - throws Error { + private static ObjectArrayList fixMinuses(final MathContext context, + final ObjectArrayList features) throws Error { final ObjectArrayList process = new ObjectArrayList<>(); Feature lastFeature = null; for (final Feature f : features) { if (f instanceof FeatureChar && (((FeatureChar) f).ch == MathematicalSymbols.SUBTRACTION || ((FeatureChar) f).ch == MathematicalSymbols.MINUS)) { boolean isNegativeOfNumber = false; - if (lastFeature == null) { + if (lastFeature == null) isNegativeOfNumber = true; - } else if (lastFeature instanceof FeatureChar) { + else if (lastFeature instanceof FeatureChar) { final FeatureChar lcf = (FeatureChar) lastFeature; final char[] operators = MathematicalSymbols.functionsAndSignums; - for (final char operator : operators) { + for (final char operator : operators) if (lcf.ch == operator) { isNegativeOfNumber = true; break; } - } } - if (isNegativeOfNumber) { + if (isNegativeOfNumber) process.add(new FeatureChar(MathematicalSymbols.MINUS)); - } else { + else process.add(new FeatureChar(MathematicalSymbols.SUBTRACTION)); - } - } else { + } else process.add(f); - } lastFeature = f; } return process; @@ -294,27 +275,25 @@ public class MathParser { /** * Make powers [12][^[15]] => [[12]^[15]] - * + * * @param context * @param features * @return * @throws Error */ - private static ObjectArrayList makePowers(MathContext context, ObjectArrayList features) - throws Error { + private static ObjectArrayList makePowers(final MathContext context, + final ObjectArrayList features) throws Error { final ObjectArrayList process = new ObjectArrayList<>(); Feature lastFeature = null; for (final Feature f : features) { if (f instanceof FeaturePowerChar) { - if (lastFeature != null) { + if (lastFeature != null) process.set(process.size() - 1, new FeaturePower(lastFeature.toFunction(context), ((FeaturePowerChar) f).getChild())); - } else { + else process.add(f); - } - } else { + } else process.add(f); - } lastFeature = f; } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/MathParserStep.java b/core/src/main/java/it/cavallium/warppi/math/parser/MathParserStep.java index a54eb649..afb4e433 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/MathParserStep.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/MathParserStep.java @@ -7,22 +7,22 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Join number and variables together ([2][4][x] => [[24]*[x]]) - * + * * @author Andrea Cavalli * */ public interface MathParserStep { /** - * + * * @param f * @param curIndex * @param process * @return true if something changed */ - public boolean eval(IntWrapper curIndex, Function lastFunction, Function currentFunction, + boolean eval(IntWrapper curIndex, Function lastFunction, Function currentFunction, ObjectArrayList functionsfunctionsList) throws Error; - public boolean requiresReversedIteration(); + boolean requiresReversedIteration(); - public String getStepName(); + String getStepName(); } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureChar.java b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureChar.java index 9b2610f0..78c768ca 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureChar.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureChar.java @@ -8,12 +8,12 @@ public class FeatureChar implements Feature { public final char ch; - public FeatureChar(char ch) { + public FeatureChar(final char ch) { this.ch = ch; } @Override - public Function toFunction(MathContext context) { + public Function toFunction(final MathContext context) { return null; } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureDivision.java b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureDivision.java index 513b16e8..2224b7ae 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureDivision.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureDivision.java @@ -5,12 +5,12 @@ import it.cavallium.warppi.math.functions.Division; public class FeatureDivision extends FeatureDoubleImpl { - public FeatureDivision(Object child1, Object child2) { + public FeatureDivision(final Object child1, final Object child2) { super(child1, child2); } @Override - public Division toFunction(MathContext context) { + public Division toFunction(final MathContext context) { return new Division(context, getFunction1(), getFunction2()); } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureDoubleImpl.java b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureDoubleImpl.java index 5227d8d0..e5341dc7 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureDoubleImpl.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureDoubleImpl.java @@ -7,7 +7,7 @@ public abstract class FeatureDoubleImpl implements FeatureDouble { private Object child_1; private Object child_2; - public FeatureDoubleImpl(Object child1, Object child2) { + public FeatureDoubleImpl(final Object child1, final Object child2) { child_1 = child1; child_2 = child2; } @@ -18,7 +18,7 @@ public abstract class FeatureDoubleImpl implements FeatureDouble { } @Override - public void setChild1(Object obj) { + public void setChild1(final Object obj) { child_1 = obj; } @@ -28,7 +28,7 @@ public abstract class FeatureDoubleImpl implements FeatureDouble { } @Override - public void setChild2(Object obj) { + public void setChild2(final Object obj) { child_2 = obj; } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureLogarithm.java b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureLogarithm.java index 7493a23a..ad3995b2 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureLogarithm.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureLogarithm.java @@ -6,12 +6,12 @@ import it.cavallium.warppi.util.Error; public class FeatureLogarithm extends FeatureDoubleImpl { - public FeatureLogarithm(Object child1, Object child2) { + public FeatureLogarithm(final Object child1, final Object child2) { super(child1, child2); } @Override - public Logarithm toFunction(MathContext context) throws Error { + public Logarithm toFunction(final MathContext context) throws Error { return new Logarithm(context, getFunction1(), getFunction2()); } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureMultiplication.java b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureMultiplication.java index e7f4075b..bcb8d6c8 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureMultiplication.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureMultiplication.java @@ -5,12 +5,12 @@ import it.cavallium.warppi.math.functions.Multiplication; public class FeatureMultiplication extends FeatureDoubleImpl { - public FeatureMultiplication(Object child1, Object child2) { + public FeatureMultiplication(final Object child1, final Object child2) { super(child1, child2); } @Override - public Multiplication toFunction(MathContext context) { + public Multiplication toFunction(final MathContext context) { return new Multiplication(context, getFunction1(), getFunction2()); } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureNumber.java b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureNumber.java index ce4095df..f17479d8 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureNumber.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureNumber.java @@ -9,11 +9,11 @@ import it.cavallium.warppi.util.Error; public class FeatureNumber implements FeatureBasic { private String numberString; - public FeatureNumber(char c) { + public FeatureNumber(final char c) { numberString = c + ""; } - public FeatureNumber(String s) { + public FeatureNumber(final String s) { numberString = s; } @@ -25,24 +25,22 @@ public class FeatureNumber implements FeatureBasic { return numberString; } - public void append(char ch) { + public void append(final char ch) { numberString += ch; } @Override - public Number toFunction(MathContext context) throws Error { + public Number toFunction(final MathContext context) throws Error { String nmbstr = getNumberString(); - if (nmbstr.charAt(0) == '.') { + if (nmbstr.charAt(0) == '.') nmbstr = '0' + nmbstr; - } else if (nmbstr.charAt(nmbstr.length() - 1) == '.') { + else if (nmbstr.charAt(nmbstr.length() - 1) == '.') nmbstr += "0"; - } else if (nmbstr.length() == 1) { - if (nmbstr.charAt(0) == MathematicalSymbols.MINUS) { + else if (nmbstr.length() == 1) + if (nmbstr.charAt(0) == MathematicalSymbols.MINUS) nmbstr += "1"; - } else if (nmbstr.charAt(0) == MathematicalSymbols.SUBTRACTION) { + else if (nmbstr.charAt(0) == MathematicalSymbols.SUBTRACTION) nmbstr += "1"; - } - } return new Number(context, nmbstr); } } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureParenthesis.java b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureParenthesis.java index 6bc9b3d2..805d056f 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureParenthesis.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureParenthesis.java @@ -7,12 +7,12 @@ import it.cavallium.warppi.util.Error; public class FeatureParenthesis extends FeatureSingleImpl { - public FeatureParenthesis(Object child) { + public FeatureParenthesis(final Object child) { super(child); } @Override - public Function toFunction(MathContext context) throws Error { + public Function toFunction(final MathContext context) throws Error { return new Expression(context, getFunction1()); } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeaturePower.java b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeaturePower.java index 67d5be7a..4dde7574 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeaturePower.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeaturePower.java @@ -6,12 +6,12 @@ import it.cavallium.warppi.util.Error; public class FeaturePower extends FeatureDoubleImpl { - public FeaturePower(Object child1, Object child2) { + public FeaturePower(final Object child1, final Object child2) { super(child1, child2); } @Override - public Power toFunction(MathContext context) throws Error { + public Power toFunction(final MathContext context) throws Error { return new Power(context, getFunction1(), getFunction2()); } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeaturePowerChar.java b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeaturePowerChar.java index 3f04ce63..73094e16 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeaturePowerChar.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeaturePowerChar.java @@ -6,12 +6,12 @@ import it.cavallium.warppi.util.Error; public class FeaturePowerChar extends FeatureSingleImpl { - public FeaturePowerChar(Object child) { + public FeaturePowerChar(final Object child) { super(child); } @Override - public Function toFunction(MathContext context) throws Error { + public Function toFunction(final MathContext context) throws Error { return null; } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSine.java b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSine.java index fb2281ce..703dde99 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSine.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSine.java @@ -7,12 +7,12 @@ import it.cavallium.warppi.util.Error; public class FeatureSine extends FeatureSingleImpl { - public FeatureSine(Object child) { + public FeatureSine(final Object child) { super(child); } @Override - public Function toFunction(MathContext context) throws Error { + public Function toFunction(final MathContext context) throws Error { return new Sine(context, getFunction1()); } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSingleImpl.java b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSingleImpl.java index 37d9dfd1..9005097c 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSingleImpl.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSingleImpl.java @@ -6,7 +6,7 @@ import it.cavallium.warppi.math.parser.features.interfaces.FeatureSingle; public abstract class FeatureSingleImpl implements FeatureSingle { private Object child; - public FeatureSingleImpl(Object child) { + public FeatureSingleImpl(final Object child) { this.child = child; } @@ -20,7 +20,7 @@ public abstract class FeatureSingleImpl implements FeatureSingle { } @Override - public void setChild(Object obj) { + public void setChild(final Object obj) { child = obj; } } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSquareRoot.java b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSquareRoot.java index 04b6a86a..c179bfb3 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSquareRoot.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSquareRoot.java @@ -6,12 +6,12 @@ import it.cavallium.warppi.util.Error; public class FeatureSquareRoot extends FeatureSingleImpl { - public FeatureSquareRoot(Object child) { + public FeatureSquareRoot(final Object child) { super(child); } @Override - public RootSquare toFunction(MathContext context) throws Error { + public RootSquare toFunction(final MathContext context) throws Error { return new RootSquare(context, getFunction1()); } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSubtraction.java b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSubtraction.java index d07953db..ffb35cc1 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSubtraction.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSubtraction.java @@ -7,12 +7,12 @@ import it.cavallium.warppi.util.Error; public class FeatureSubtraction extends FeatureDoubleImpl { - public FeatureSubtraction(Object child1, Object child2) { + public FeatureSubtraction(final Object child1, final Object child2) { super(child1, child2); } @Override - public Function toFunction(MathContext context) throws Error { + public Function toFunction(final MathContext context) throws Error { return new Subtraction(context, getFunction1(), getFunction2()); } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSum.java b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSum.java index 28ec5ae6..ac6a58d3 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSum.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSum.java @@ -6,12 +6,12 @@ import it.cavallium.warppi.util.Error; public class FeatureSum extends FeatureDoubleImpl { - public FeatureSum(Object child1, Object child2) { + public FeatureSum(final Object child1, final Object child2) { super(child1, child2); } @Override - public Sum toFunction(MathContext context) throws Error { + public Sum toFunction(final MathContext context) throws Error { return new Sum(context, getFunction1(), getFunction2()); } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSumSubtraction.java b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSumSubtraction.java index 16c34f11..8b7eb6c4 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSumSubtraction.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureSumSubtraction.java @@ -6,12 +6,12 @@ import it.cavallium.warppi.util.Error; public class FeatureSumSubtraction extends FeatureDoubleImpl { - public FeatureSumSubtraction(Object child1, Object child2) { + public FeatureSumSubtraction(final Object child1, final Object child2) { super(child1, child2); } @Override - public SumSubtraction toFunction(MathContext context) throws Error { + public SumSubtraction toFunction(final MathContext context) throws Error { return new SumSubtraction(context, getFunction1(), getFunction2()); } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureVariable.java b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureVariable.java index 25d4decf..589bb1b4 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureVariable.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/features/FeatureVariable.java @@ -9,13 +9,13 @@ public class FeatureVariable extends FeatureChar { public V_TYPE varType; - public FeatureVariable(char ch, V_TYPE varType) { + public FeatureVariable(final char ch, final V_TYPE varType) { super(ch); this.varType = varType; } @Override - public Function toFunction(MathContext context) { + public Function toFunction(final MathContext context) { return new Variable(context, ch, varType); } } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/features/interfaces/Feature.java b/core/src/main/java/it/cavallium/warppi/math/parser/features/interfaces/Feature.java index b4a1b1f4..bb7c9403 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/features/interfaces/Feature.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/features/interfaces/Feature.java @@ -6,6 +6,6 @@ import it.cavallium.warppi.util.Error; public abstract interface Feature { - public Function toFunction(MathContext context) throws Error; + Function toFunction(MathContext context) throws Error; } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/features/interfaces/FeatureDouble.java b/core/src/main/java/it/cavallium/warppi/math/parser/features/interfaces/FeatureDouble.java index 645141fb..69aaeff6 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/features/interfaces/FeatureDouble.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/features/interfaces/FeatureDouble.java @@ -1,11 +1,11 @@ package it.cavallium.warppi.math.parser.features.interfaces; public interface FeatureDouble extends Feature { - public Object getChild1(); + Object getChild1(); - public void setChild1(Object obj); + void setChild1(Object obj); - public Object getChild2(); + Object getChild2(); - public void setChild2(Object obj); + void setChild2(Object obj); } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/features/interfaces/FeatureMultiple.java b/core/src/main/java/it/cavallium/warppi/math/parser/features/interfaces/FeatureMultiple.java index 62bc2b9c..88c7ee98 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/features/interfaces/FeatureMultiple.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/features/interfaces/FeatureMultiple.java @@ -1,15 +1,15 @@ package it.cavallium.warppi.math.parser.features.interfaces; public interface FeatureMultiple extends Feature { - public Object[] getChildren(); + Object[] getChildren(); - public Object getChild(int index); + Object getChild(int index); - public int getChildCount(); + int getChildCount(); - public void setChild(int index, Object obj); + void setChild(int index, Object obj); - public void setChildren(Object[] objs); + void setChildren(Object[] objs); - public void addChild(Object obj); + void addChild(Object obj); } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/features/interfaces/FeatureSingle.java b/core/src/main/java/it/cavallium/warppi/math/parser/features/interfaces/FeatureSingle.java index 70f0571d..470371b9 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/features/interfaces/FeatureSingle.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/features/interfaces/FeatureSingle.java @@ -1,7 +1,7 @@ package it.cavallium.warppi.math.parser.features.interfaces; public interface FeatureSingle extends Feature { - public Object getChild(); + Object getChild(); - public void setChild(Object obj); + void setChild(Object obj); } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/steps/AddImplicitMultiplications.java b/core/src/main/java/it/cavallium/warppi/math/parser/steps/AddImplicitMultiplications.java index 89d77218..0784d2c3 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/steps/AddImplicitMultiplications.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/steps/AddImplicitMultiplications.java @@ -11,26 +11,25 @@ public class AddImplicitMultiplications implements MathParserStep { private final MathContext context; - public AddImplicitMultiplications(MathContext context) { + public AddImplicitMultiplications(final MathContext context) { this.context = context; } @Override - public boolean eval(IntWrapper curIndex, Function lastFunction, Function currentFunction, - ObjectArrayList functionsList) { + public boolean eval(final IntWrapper curIndex, final Function lastFunction, final Function currentFunction, + final ObjectArrayList functionsList) { if (currentFunction instanceof Function) { if (lastFunction instanceof Function) { functionsList.set(curIndex.i, new Multiplication(context, currentFunction, lastFunction)); functionsList.remove(curIndex.i + 1); return true; } - } else if (currentFunction instanceof Function) { + } else if (currentFunction instanceof Function) if (lastFunction instanceof Function) { functionsList.set(curIndex.i, new Multiplication(context, currentFunction, lastFunction)); functionsList.remove(curIndex.i + 1); return true; } - } return false; } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/steps/FixMultiplicationsAndDivisions.java b/core/src/main/java/it/cavallium/warppi/math/parser/steps/FixMultiplicationsAndDivisions.java index c2fbb7c6..c96a998e 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/steps/FixMultiplicationsAndDivisions.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/steps/FixMultiplicationsAndDivisions.java @@ -12,10 +12,10 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class FixMultiplicationsAndDivisions implements MathParserStep { @Override - public boolean eval(IntWrapper curIndex, Function lastFunction, Function currentFunction, - ObjectArrayList functionsList) throws Error { - if (currentFunction instanceof Multiplication || currentFunction instanceof Division) { - if (currentFunction.getParameter(0) == null && currentFunction.getParameter(1) == null) { + public boolean eval(final IntWrapper curIndex, final Function lastFunction, final Function currentFunction, + final ObjectArrayList functionsList) throws Error { + if (currentFunction instanceof Multiplication || currentFunction instanceof Division) + if (currentFunction.getParameter(0) == null && currentFunction.getParameter(1) == null) if (curIndex.i - 1 >= 0 && curIndex.i + 1 < functionsList.size()) { final Function next = functionsList.get(curIndex.i + 1); final Function prev = functionsList.get(curIndex.i - 1); @@ -24,13 +24,8 @@ public class FixMultiplicationsAndDivisions implements MathParserStep { functionsList.remove(curIndex.i - 1); curIndex.i--; return true; - } else { - if (currentFunction.getParameter(0) == null || currentFunction.getParameter(1) == null) { - throw new Error(Errors.MISSING_ARGUMENTS, "There is a function at the end without any argument specified."); - } - } - } - } + } else if (currentFunction.getParameter(0) == null || currentFunction.getParameter(1) == null) + throw new Error(Errors.MISSING_ARGUMENTS, "There is a function at the end without any argument specified."); return false; } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/steps/FixSingleFunctionArgs.java b/core/src/main/java/it/cavallium/warppi/math/parser/steps/FixSingleFunctionArgs.java index 94128204..ccdda3ba 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/steps/FixSingleFunctionArgs.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/steps/FixSingleFunctionArgs.java @@ -10,26 +10,25 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Puts the argument of Single Functions inside them - * + * * @author Andrea Cavalli * */ public class FixSingleFunctionArgs implements MathParserStep { @Override - public boolean eval(IntWrapper curIndex, Function lastFunction, Function currentFunction, - ObjectArrayList functionsList) throws Error { - if (currentFunction instanceof FunctionSingle) { + public boolean eval(final IntWrapper curIndex, final Function lastFunction, final Function currentFunction, + final ObjectArrayList functionsList) throws Error { + if (currentFunction instanceof FunctionSingle) if (((FunctionSingle) currentFunction).getParameter() == null) { - if (lastFunction == null) { + if (lastFunction == null) throw new Error(Errors.MISSING_ARGUMENTS, "There is a function at the end without any argument specified."); - } else { + else { ((FunctionSingle) currentFunction).setParameter(lastFunction); functionsList.remove(curIndex.i + 1); } return true; } - } return false; } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/steps/FixSumsAndSubtractions.java b/core/src/main/java/it/cavallium/warppi/math/parser/steps/FixSumsAndSubtractions.java index 8a6a6610..e9aa8b73 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/steps/FixSumsAndSubtractions.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/steps/FixSumsAndSubtractions.java @@ -13,10 +13,10 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; public class FixSumsAndSubtractions implements MathParserStep { @Override - public boolean eval(IntWrapper curIndex, Function lastFunction, Function currentFunction, - ObjectArrayList functionsList) throws Error { - if (currentFunction instanceof Sum || currentFunction instanceof Subtraction || currentFunction instanceof SumSubtraction) { - if (currentFunction.getParameter(0) == null && currentFunction.getParameter(1) == null) { + public boolean eval(final IntWrapper curIndex, final Function lastFunction, final Function currentFunction, + final ObjectArrayList functionsList) throws Error { + if (currentFunction instanceof Sum || currentFunction instanceof Subtraction || currentFunction instanceof SumSubtraction) + if (currentFunction.getParameter(0) == null && currentFunction.getParameter(1) == null) if (curIndex.i - 1 >= 0 && curIndex.i + 1 < functionsList.size()) { final Function next = functionsList.get(curIndex.i + 1); final Function prev = functionsList.get(curIndex.i - 1); @@ -25,13 +25,8 @@ public class FixSumsAndSubtractions implements MathParserStep { functionsList.remove(curIndex.i - 1); curIndex.i--; return true; - } else { - if (currentFunction.getParameter(0) == null || currentFunction.getParameter(1) == null) { - throw new Error(Errors.MISSING_ARGUMENTS, "There is a function at the end without any argument specified."); - } - } - } - } + } else if (currentFunction.getParameter(0) == null || currentFunction.getParameter(1) == null) + throw new Error(Errors.MISSING_ARGUMENTS, "There is a function at the end without any argument specified."); return false; } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/steps/JoinNumberAndVariables.java b/core/src/main/java/it/cavallium/warppi/math/parser/steps/JoinNumberAndVariables.java index 254f4ee3..1a172bac 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/steps/JoinNumberAndVariables.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/steps/JoinNumberAndVariables.java @@ -14,14 +14,14 @@ public class JoinNumberAndVariables implements MathParserStep { private final MathContext context; - public JoinNumberAndVariables(MathContext context) { + public JoinNumberAndVariables(final MathContext context) { this.context = context; } @Override - public boolean eval(IntWrapper curIndex, Function lastFunction, Function currentFunction, - ObjectArrayList functionsList) { - if (currentFunction instanceof Number | currentFunction instanceof Variable | currentFunction instanceof Division) { + public boolean eval(final IntWrapper curIndex, final Function lastFunction, final Function currentFunction, + final ObjectArrayList functionsList) { + if (currentFunction instanceof Number | currentFunction instanceof Variable | currentFunction instanceof Division) if (lastFunction instanceof Variable | lastFunction instanceof Number | (lastFunction instanceof Multiplication && ((Multiplication) lastFunction).getParameter2() != null)) { final Function a = currentFunction; final Function b = lastFunction; @@ -29,7 +29,6 @@ public class JoinNumberAndVariables implements MathParserStep { functionsList.remove(curIndex.i + 1); return true; } - } return false; } diff --git a/core/src/main/java/it/cavallium/warppi/math/parser/steps/RemoveParentheses.java b/core/src/main/java/it/cavallium/warppi/math/parser/steps/RemoveParentheses.java index ae5ee319..543c9cf3 100644 --- a/core/src/main/java/it/cavallium/warppi/math/parser/steps/RemoveParentheses.java +++ b/core/src/main/java/it/cavallium/warppi/math/parser/steps/RemoveParentheses.java @@ -12,19 +12,18 @@ public class RemoveParentheses implements MathParserStep { @SuppressWarnings("unused") private final MathContext context; - public RemoveParentheses(MathContext context) { + public RemoveParentheses(final MathContext context) { this.context = context; } @Override - public boolean eval(IntWrapper curIndex, Function lastFunction, Function currentFunction, - ObjectArrayList functionsList) { + public boolean eval(final IntWrapper curIndex, final Function lastFunction, final Function currentFunction, + final ObjectArrayList functionsList) { if (currentFunction instanceof Expression) { - if (((Expression) currentFunction).getParameter() == null) { + if (((Expression) currentFunction).getParameter() == null) functionsList.remove(curIndex.i); - } else { + else functionsList.set(curIndex.i, ((Expression) currentFunction).getParameter()); - } return true; } return false; diff --git a/core/src/main/java/it/cavallium/warppi/math/rules/Rule.java b/core/src/main/java/it/cavallium/warppi/math/rules/Rule.java index a2d658a1..9c2a8108 100644 --- a/core/src/main/java/it/cavallium/warppi/math/rules/Rule.java +++ b/core/src/main/java/it/cavallium/warppi/math/rules/Rule.java @@ -6,29 +6,29 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Rule interface - * + * * @author Andrea Cavalli * */ public interface Rule { /** * Get rule name - * + * * @return */ - public default String getRuleName() { + default String getRuleName() { return "UnnamedRule1"; } /** * Get rule type - * + * * @return */ - public RuleType getRuleType(); + RuleType getRuleType(); /** - * + * * @param func * @return *
    @@ -39,5 +39,5 @@ public interface Rule { *
* @throws Error */ - public ObjectArrayList execute(Function func) throws Error, InterruptedException; + ObjectArrayList execute(Function func) throws Error, InterruptedException; } \ No newline at end of file diff --git a/core/src/main/java/it/cavallium/warppi/math/rules/RulesManager.java b/core/src/main/java/it/cavallium/warppi/math/rules/RulesManager.java index a5f3ac86..c31a09d2 100644 --- a/core/src/main/java/it/cavallium/warppi/math/rules/RulesManager.java +++ b/core/src/main/java/it/cavallium/warppi/math/rules/RulesManager.java @@ -13,6 +13,7 @@ import java.util.List; import it.cavallium.warppi.Engine; import it.cavallium.warppi.Platform.ConsoleUtils; +import it.cavallium.warppi.Platform.StorageUtils; import it.cavallium.warppi.Platform.URLClassLoader; import it.cavallium.warppi.StaticVars; import it.cavallium.warppi.math.Function; @@ -30,33 +31,30 @@ public class RulesManager { private RulesManager() {} - @SuppressWarnings({ "unchecked", "unused" }) + @SuppressWarnings({ "unchecked" }) public static void initialize() { Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Loading the rules"); - rules = new ObjectArrayList[RuleType.values().length]; - for (final RuleType val : RuleType.values()) { - rules[val.ordinal()] = new ObjectArrayList<>(); - } + RulesManager.rules = new ObjectArrayList[RuleType.values().length]; + for (final RuleType val : RuleType.values()) + RulesManager.rules[val.ordinal()] = new ObjectArrayList<>(); try { boolean compiledSomething = false; InputStream defaultRulesList; try { defaultRulesList = Engine.getPlatform().getStorageUtils().getResourceStream("/default-rules.lst"); - } catch (IOException ex) { + } catch (final IOException ex) { throw new FileNotFoundException("default-rules.lst not found!"); } final List ruleLines = new ArrayList<>(); final File rulesPath = Engine.getPlatform().getStorageUtils().get("rules/"); - if (rulesPath.exists()) { - for (File f : Engine.getPlatform().getStorageUtils().walk(rulesPath)) { + if (rulesPath.exists()) + for (final File f : Engine.getPlatform().getStorageUtils().walk(rulesPath)) if (f.toString().endsWith(".java")) { String path = Engine.getPlatform().getStorageUtils().relativize(rulesPath, f).toString(); path = path.substring(0, path.length() - ".java".length()); ruleLines.add(path); Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Found external rule: " + f.getAbsolutePath()); } - } - } ruleLines.addAll(Engine.getPlatform().getStorageUtils().readAllLines(defaultRulesList)); final File tDir = Engine.getPlatform().getStorageUtils().resolve(Engine.getPlatform().getStorageUtils().get(System.getProperty("java.io.tmpdir"), "WarpPi-Calculator"), "rules-rt"); @@ -67,34 +65,31 @@ public class RulesManager { File cacheFilePath = null; cacheFilePath = new File("math-rules-cache.zip"); boolean cacheFileExists = false; - if (Engine.getPlatform().isJavascript()) { + if (Engine.getPlatform().isJavascript()) Engine.getPlatform().loadPlatformRules(); - } else { + else { if (cacheFilePath.exists()) { cacheFileExists = true; cacheFileStream = new FileInputStream(cacheFilePath); - } else { + } else try { cacheFileStream = Engine.getPlatform().getStorageUtils().getResourceStream("/math-rules-cache.zip");//Paths.get(Utils.getJarDirectory().toString()).resolve("math-rules-cache.zip").toAbsolutePath( org.apache.commons.io.FileUtils.copyInputStreamToFile(cacheFileStream, cacheFilePath); cacheFileExists = true; - } catch (IOException ex) { //File does not exists. + } catch (final IOException ex) { //File does not exists. } - } boolean useCache = false; - if (cacheFileExists) { + if (cacheFileExists) try { - if (tDir.exists()) { + if (tDir.exists()) tDir.delete(); - } Engine.getPlatform().unzip(cacheFilePath.toString(), tDir.getParent().toString(), ""); useCache = !StaticVars.startupArguments.isUncached(); } catch (final Exception ex) { ex.printStackTrace(); } - } - for (final String rulesLine : ruleLines) { + for (final String rulesLine : ruleLines) if (rulesLine.length() > 0) { final String[] ruleDetails = rulesLine.split(",", 1); final String ruleName = ruleDetails[0]; @@ -103,57 +98,51 @@ public class RulesManager { final String pathWithoutExtension = "/rules/" + ruleNameEscaped; final String scriptFile = pathWithoutExtension + ".java"; final InputStream resourcePath = Engine.getPlatform().getStorageUtils().getResourceStream(scriptFile); - if (resourcePath == null) { + if (resourcePath == null) System.err.println(new FileNotFoundException("/rules/" + ruleName + ".java not found!")); - } else { + else { Rule r = null; - if (useCache) { + if (useCache) try { Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_MIN, "RulesManager", ruleName, "Trying to load cached rule"); - r = loadClassRuleFromSourceFile(scriptFile, tDir); - if (r != null) { + r = RulesManager.loadClassRuleFromSourceFile(scriptFile, tDir); + if (r != null) Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_MIN, "RulesManager", ruleName, "Loaded cached rule"); - } } catch (final Exception e) { e.printStackTrace(); - Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_NODEBUG, "RulesManager", ruleName, "Can't load the rule "+ ruleNameEscaped +"!"); + Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_NODEBUG, "RulesManager", ruleName, "Can't load the rule " + ruleNameEscaped + "!"); } - } if (r == null || !useCache) { Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_MIN, "RulesManager", ruleName, "This rule is not cached. Compiling"); try { - r = compileJavaRule(scriptFile, tDir); + r = RulesManager.compileJavaRule(scriptFile, tDir); compiledSomething = true; } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | IOException e) { e.printStackTrace(); } } - if (r != null) { + if (r != null) RulesManager.addRule(r); - } } } - } } Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Loaded all the rules successfully"); if (!Engine.getPlatform().isJavascript() && compiledSomething) { - if (cacheFileExists || cacheFilePath.exists()) { + if (cacheFileExists || cacheFilePath.exists()) cacheFilePath.delete(); - } Engine.getPlatform().zip(tDir.toString(), cacheFilePath.toString(), ""); Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Cached the compiled rules"); } - if (cacheFileStream != null) { + if (cacheFileStream != null) cacheFileStream.close(); - } } catch (URISyntaxException | IOException e) { e.printStackTrace(); Engine.getPlatform().exit(1); } } - public static Rule compileJavaRule(String scriptFile, File tDir) throws IOException, URISyntaxException, + public static Rule compileJavaRule(final String scriptFile, final File tDir) throws IOException, URISyntaxException, InstantiationException, IllegalAccessException, ClassNotFoundException { final InputStream resource = Engine.getPlatform().getStorageUtils().getResourceStream(scriptFile); final String text = Engine.getPlatform().getStorageUtils().read(resource); @@ -168,32 +157,29 @@ public class RulesManager { final File tDirPath = Engine.getPlatform().getStorageUtils().getParent(Engine.getPlatform().getStorageUtils().resolve(tDir, javaClassNameAndPath.replace('.', File.separatorChar))); final File tFileJava = Engine.getPlatform().getStorageUtils().resolve(tDirPath, javaClassNameOnly + ".java"); final File tFileClass = Engine.getPlatform().getStorageUtils().resolve(tDirPath, javaClassNameOnly + ".class"); - if (!tDirPath.exists()) { + if (!tDirPath.exists()) Engine.getPlatform().getStorageUtils().createDirectories(tDirPath); - } - if (tFileJava.exists()) { + if (tFileJava.exists()) tFileJava.delete(); - } - Engine.getPlatform().getStorageUtils().write(tFileJava, javaCode.getBytes("UTF-8"), Engine.getPlatform().getStorageUtils().OpenOptionWrite, Engine.getPlatform().getStorageUtils().OpenOptionCreate); + Engine.getPlatform().getStorageUtils(); + Engine.getPlatform().getStorageUtils(); + Engine.getPlatform().getStorageUtils().write(tFileJava, javaCode.getBytes("UTF-8"), StorageUtils.OpenOptionWrite, StorageUtils.OpenOptionCreate); final boolean compiled = Engine.getPlatform().compile(new String[] { "-nowarn", "-1.8", tFileJava.toString() }, new PrintWriter(System.out), new PrintWriter(System.err)); - if (StaticVars.startupArguments.isUncached()) { + if (StaticVars.startupArguments.isUncached()) tFileJava.deleteOnExit(); - } else { + else tFileJava.delete(); - } if (compiled) { tFileClass.deleteOnExit(); - return loadClassRuleDirectly(javaClassNameAndPath, tDir); - } else { + return RulesManager.loadClassRuleDirectly(javaClassNameAndPath, tDir); + } else throw new IOException("Can't build script file '" + scriptFile + "'"); - } - } else { + } else throw new IOException("Can't build script file '" + scriptFile + "', the header is missing or wrong."); - } } - public static Rule loadClassRuleFromSourceFile(String scriptFile, File tDir) throws IOException, URISyntaxException, - InstantiationException, IllegalAccessException, ClassNotFoundException { + public static Rule loadClassRuleFromSourceFile(final String scriptFile, final File tDir) throws IOException, + URISyntaxException, InstantiationException, IllegalAccessException, ClassNotFoundException { final InputStream resource = Engine.getPlatform().getStorageUtils().getResourceStream(scriptFile); final String text = Engine.getPlatform().getStorageUtils().read(resource); final String[] textArray = text.split("\\n", 6); @@ -202,17 +188,16 @@ public class RulesManager { Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_VERBOSE, "RulesManager", "Rule java class name: " + javaClassName); final String javaClassNameAndPath = new StringBuilder("it.cavallium.warppi.math.rules.").append(javaClassName).toString(); try { - return loadClassRuleDirectly(javaClassNameAndPath, tDir); + return RulesManager.loadClassRuleDirectly(javaClassNameAndPath, tDir); } catch (final Exception ex) { ex.printStackTrace(); return null; } - } else { + } else throw new IOException("Can't load script file '" + scriptFile + "', the header is missing or wrong."); - } } - public static Rule loadClassRuleDirectly(String javaClassNameAndPath, File tDir) throws IOException, + public static Rule loadClassRuleDirectly(final String javaClassNameAndPath, final File tDir) throws IOException, URISyntaxException, InstantiationException, IllegalAccessException, ClassNotFoundException { final URLClassLoader cl = Engine.getPlatform().newURLClassLoader(new URL[] { tDir.toURI().toURL() }); final Class aClass = cl.loadClass(javaClassNameAndPath); @@ -224,12 +209,12 @@ public class RulesManager { ObjectArrayList uselessResult = null; boolean uselessVariable = false; for (final RuleType val : RuleType.values()) { - final ObjectArrayList ruleList = rules[val.ordinal()]; + final ObjectArrayList ruleList = RulesManager.rules[val.ordinal()]; for (final Rule rule : ruleList) { String ruleName = ""; try { ruleName = rule.getRuleName(); - final ObjectArrayList uselessResult2 = rule.execute(generateUselessExpression()); + final ObjectArrayList uselessResult2 = rule.execute(RulesManager.generateUselessExpression()); uselessVariable = (uselessResult == null ? new ObjectArrayList<>() : uselessResult).equals(uselessResult2); uselessResult = uselessResult2; } catch (final Exception e) { @@ -241,7 +226,7 @@ public class RulesManager { } } try { - new MathSolver(generateUselessExpression()).solveAllSteps(); + new MathSolver(RulesManager.generateUselessExpression()).solveAllSteps(); } catch (InterruptedException | Error e) { e.printStackTrace(); } @@ -254,8 +239,8 @@ public class RulesManager { return expr; } - public static void addRule(Rule rule) { - rules[rule.getRuleType().ordinal()].add(rule); + public static void addRule(final Rule rule) { + RulesManager.rules[rule.getRuleType().ordinal()].add(rule); Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_MIN, "RulesManager", rule.getRuleName(), "Loaded as " + rule.getRuleType() + " rule"); } } diff --git a/core/src/main/java/it/cavallium/warppi/math/rules/methods/DivisionRule1.java b/core/src/main/java/it/cavallium/warppi/math/rules/methods/DivisionRule1.java index 0e89ea9e..8df1d494 100644 --- a/core/src/main/java/it/cavallium/warppi/math/rules/methods/DivisionRule1.java +++ b/core/src/main/java/it/cavallium/warppi/math/rules/methods/DivisionRule1.java @@ -11,21 +11,21 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Division method
* Example: (XY)/(YZ) = Y/Y * X/Z - * + * * @author Andrea Cavalli * */ public class DivisionRule1 { - public static boolean compare(Division f) throws InterruptedException { + public static boolean compare(final Division f) throws InterruptedException { return false;//TODO: return f.getParameter1().isSimplified() && f.getParameter2().isSimplified() && (f.getParameter1() instanceof Multiplication || f.getParameter2() instanceof Multiplication) && getFirstWorkingDivisionCouple(getDivisionElements(f)) != null; } - public static ObjectArrayList execute(Division f) throws Error, InterruptedException { + public static ObjectArrayList execute(final Division f) throws Error, InterruptedException { final MathContext root = f.getMathContext(); Function result; - final ObjectArrayList[] elements = getDivisionElements(f); - final int[] workingElementCouple = getFirstWorkingDivisionCouple(elements); + final ObjectArrayList[] elements = DivisionRule1.getDivisionElements(f); + final int[] workingElementCouple = DivisionRule1.getFirstWorkingDivisionCouple(elements); final Function elem1 = elements[0].get(workingElementCouple[0]); final Function elem2 = elements[1].get(workingElementCouple[1]); @@ -46,20 +46,17 @@ public class DivisionRule1 { Function prec; for (int part = 0; part < 2; part++) { prec = null; - for (int i = size[part] - 1; i >= 0; i--) { - if (i != workingElementCouple[part]) { - if (prec == null) { + for (int i = size[part] - 1; i >= 0; i--) + if (i != workingElementCouple[part]) + if (prec == null) prec = elements[part].get(i); - } else { + else { final Function a = elements[part].get(i); final Function b = prec; prec = new Multiplication(root, a, b); } - } - } - if (prec == null) { + if (prec == null) prec = new Number(root, 1); - } resultDivisionArray[part] = prec; } @@ -71,13 +68,13 @@ public class DivisionRule1 { } @SuppressWarnings("unchecked") - private static ObjectArrayList[] getDivisionElements(Division division) throws InterruptedException { + private static ObjectArrayList[] getDivisionElements(final Division division) + throws InterruptedException { final ObjectArrayList elementsNumerator = new ObjectArrayList<>(); Function numMult = division.getParameter1(); while (numMult instanceof Multiplication) { - if (Thread.interrupted()) { + if (Thread.interrupted()) throw new InterruptedException(); - } elementsNumerator.add(((Multiplication) numMult).getParameter1()); numMult = ((Multiplication) numMult).getParameter2(); } @@ -86,9 +83,8 @@ public class DivisionRule1 { final ObjectArrayList elementsDenominator = new ObjectArrayList<>(); Function denomMult = division.getParameter2(); while (denomMult instanceof Multiplication) { - if (Thread.interrupted()) { + if (Thread.interrupted()) throw new InterruptedException(); - } elementsDenominator.add(((Multiplication) denomMult).getParameter1()); denomMult = ((Multiplication) denomMult).getParameter2(); } @@ -97,7 +93,7 @@ public class DivisionRule1 { return new ObjectArrayList[] { elementsNumerator, elementsDenominator }; } - private static int[] getFirstWorkingDivisionCouple(ObjectArrayList[] elements) + private static int[] getFirstWorkingDivisionCouple(final ObjectArrayList[] elements) throws InterruptedException { return null; //TODO: diff --git a/core/src/main/java/it/cavallium/warppi/math/rules/methods/MultiplicationMethod1.java b/core/src/main/java/it/cavallium/warppi/math/rules/methods/MultiplicationMethod1.java index 9d5fe263..53cce2dc 100644 --- a/core/src/main/java/it/cavallium/warppi/math/rules/methods/MultiplicationMethod1.java +++ b/core/src/main/java/it/cavallium/warppi/math/rules/methods/MultiplicationMethod1.java @@ -9,30 +9,29 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Multiplication method
* Example: X*3*X*2 = 6*X^2 - * + * * @author Andrea Cavalli * */ public class MultiplicationMethod1 { - public static boolean compare(Function f) throws InterruptedException { + public static boolean compare(final Function f) throws InterruptedException { return false;//TODO: return ((Multiplication) f).getParameter1().isSimplified() && ((Multiplication) f).getParameter2().isSimplified() && !(((Multiplication) f).getParameter1() instanceof Number && ((Multiplication) f).getParameter2() instanceof Number) && getFirstWorkingMultiplicationCouple(getMultiplicationElements(f)) != null; } - public static ObjectArrayList execute(Function f) throws Error, InterruptedException { + public static ObjectArrayList execute(final Function f) throws Error, InterruptedException { Function result; final MathContext root = f.getMathContext(); - final ObjectArrayList elements = getMultiplicationElements(f); - final int[] workingElementCouple = getFirstWorkingMultiplicationCouple(elements); + final ObjectArrayList elements = MultiplicationMethod1.getMultiplicationElements(f); + final int[] workingElementCouple = MultiplicationMethod1.getFirstWorkingMultiplicationCouple(elements); final Function elem1 = elements.get(workingElementCouple[0]); final Function elem2 = elements.get(workingElementCouple[1]); final int size = elements.size(); Function prec = new Multiplication(root, elem1, elem2); for (int i = size - 1; i >= 0; i--) { - if (Thread.interrupted()) { + if (Thread.interrupted()) throw new InterruptedException(); - } if (i != workingElementCouple[0] & i != workingElementCouple[1]) { final Function a = prec; final Function b = elements.get(i); @@ -50,9 +49,8 @@ public class MultiplicationMethod1 { private static ObjectArrayList getMultiplicationElements(Function mult) throws InterruptedException { final ObjectArrayList elements = new ObjectArrayList<>(); while (mult instanceof Multiplication) { - if (Thread.interrupted()) { + if (Thread.interrupted()) throw new InterruptedException(); - } elements.add(((Multiplication) mult).getParameter1()); mult = ((Multiplication) mult).getParameter2(); } @@ -60,7 +58,7 @@ public class MultiplicationMethod1 { return elements; } - private static int[] getFirstWorkingMultiplicationCouple(ObjectArrayList elements) + private static int[] getFirstWorkingMultiplicationCouple(final ObjectArrayList elements) throws InterruptedException { return null; // TODO: diff --git a/core/src/main/java/it/cavallium/warppi/math/rules/methods/SumMethod1.java b/core/src/main/java/it/cavallium/warppi/math/rules/methods/SumMethod1.java index f3b421ea..13186d7f 100644 --- a/core/src/main/java/it/cavallium/warppi/math/rules/methods/SumMethod1.java +++ b/core/src/main/java/it/cavallium/warppi/math/rules/methods/SumMethod1.java @@ -15,34 +15,33 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Sum method
* 13+sqrt(2)+5X+1 = 14+sqrt(2)+5X - * + * * @author Andrea Cavalli * */ public class SumMethod1 { - public static boolean compare(Function f) throws InterruptedException { + public static boolean compare(final Function f) throws InterruptedException { return false; //TODO: // final MathContext root = f.getMathContext(); // return (f instanceof Sum || f instanceof Subtraction) && ((FunctionOperator) f).getParameter1().isSimplified() && ((FunctionOperator) f).getParameter2().isSimplified() && !(((FunctionOperator) f).getParameter1() instanceof Number && ((FunctionOperator) f).getParameter2() instanceof Number) && getFirstWorkingSumCouple(root, getSumElements(f)) != null; } - public static ObjectArrayList execute(Function f) throws Error, InterruptedException { + public static ObjectArrayList execute(final Function f) throws Error, InterruptedException { Function result; final MathContext root = f.getMathContext(); - final ObjectArrayList elements = getSumElements(f); - final int[] workingElementCouple = getFirstWorkingSumCouple(root, elements); + final ObjectArrayList elements = SumMethod1.getSumElements(f); + final int[] workingElementCouple = SumMethod1.getFirstWorkingSumCouple(root, elements); final Function elem1 = elements.get(workingElementCouple[0]); final Function elem2 = elements.get(workingElementCouple[1]); final int size = elements.size(); Function prec = new Sum(root, elem1, elem2); - for (int i = size - 1; i >= 0; i--) { + for (int i = size - 1; i >= 0; i--) if (i != workingElementCouple[0] & i != workingElementCouple[1]) { - if (Thread.interrupted()) { + if (Thread.interrupted()) throw new InterruptedException(); - } final Function a = prec; final Function b = elements.get(i); if (b instanceof Negative) { @@ -51,11 +50,9 @@ public class SumMethod1 { } else if (b instanceof Number && ((Number) b).getTerm().compareTo(BigDecimal.ZERO) < 0) { prec = new Subtraction(root, a, ((Number) b).multiply(new Number(root, -1))); ((FunctionOperator) prec).getParameter2(); - } else { + } else prec = new Sum(root, a, b); - } } - } result = prec; @@ -68,21 +65,19 @@ public class SumMethod1 { final MathContext root = sum.getMathContext(); final ObjectArrayList elements = new ObjectArrayList<>(); while (sum instanceof Sum || sum instanceof Subtraction) { - if (Thread.interrupted()) { + if (Thread.interrupted()) throw new InterruptedException(); - } - if (sum instanceof Sum) { + if (sum instanceof Sum) elements.add(((FunctionOperator) sum).getParameter2()); - } else { + else elements.add(new Negative(root, ((FunctionOperator) sum).getParameter2())); - } sum = ((FunctionOperator) sum).getParameter1(); } elements.add(sum); return elements; } - private static int[] getFirstWorkingSumCouple(MathContext root, ObjectArrayList elements) + private static int[] getFirstWorkingSumCouple(final MathContext root, final ObjectArrayList elements) throws InterruptedException { return null; // final int size = elements.size(); diff --git a/core/src/main/java/it/cavallium/warppi/math/solver/MathSolver.java b/core/src/main/java/it/cavallium/warppi/math/solver/MathSolver.java index 8a98967c..02835d72 100644 --- a/core/src/main/java/it/cavallium/warppi/math/solver/MathSolver.java +++ b/core/src/main/java/it/cavallium/warppi/math/solver/MathSolver.java @@ -26,7 +26,7 @@ public class MathSolver { @SuppressWarnings("unchecked") private final ObjectArrayList[][] lastFunctions = new ObjectArrayList[2][stepStates.length]; - public MathSolver(Function initialFunction) { + public MathSolver(final Function initialFunction) { this.initialFunction = initialFunction; } @@ -43,17 +43,13 @@ public class MathSolver { final ObjectArrayList[] currFncHistory = new ObjectArrayList[stepStates.length]; final String stepName = "Step " + stepNumber; if (initStepState > endStepState) { - for (int i = initStepState; i < stepStates.length; i++) { + for (int i = initStepState; i < stepStates.length; i++) currFncHistory[i] = currFnc; - } - for (int i = 0; i <= initStepState; i++) { + for (int i = 0; i <= initStepState; i++) currFncHistory[i] = currFnc; - } - } else { - for (int i = initStepState; i <= endStepState; i++) { + } else + for (int i = initStepState; i <= endStepState; i++) currFncHistory[i] = currFnc; - } - } if (currFnc != null) { lastFunctions[1] = lastFunctions[0]; lastFunctions[0] = currFncHistory; @@ -63,9 +59,8 @@ public class MathSolver { Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", stepName, "Starting step " + stepStates[initStepState] + ". Input: " + currFnc); final ObjectArrayList stepResult = solveStep(lastFnc, stepState); if (stepResult != null) { - for (final Function result : stepResult) { + for (final Function result : stepResult) Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_VERBOSE, result.toString()); - } currFnc = stepResult; steps.add(currFnc); } @@ -75,53 +70,47 @@ public class MathSolver { Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", stepName, "Step result: " + stepResult); Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", stepName, "Step result details: Consecutive steps that did nothing: " + consecutiveNullSteps + ", this step did " + stepStateRepetitions + " simplifications."); Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", stepName, "Next step state: " + stepStates[endStepState]); - if (Engine.getPlatform().getSettings().isDebugEnabled()) { + if (Engine.getPlatform().getSettings().isDebugEnabled()) Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", stepName, currFnc + " is " + (checkEquals(currFnc, lastFunctions[0][endStepState]) ? "" : "not ") + "equals to [0]:" + lastFunctions[0][endStepState]); - } - if (Engine.getPlatform().getSettings().isDebugEnabled()) { + if (Engine.getPlatform().getSettings().isDebugEnabled()) Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", stepName, currFnc + " is " + (checkEquals(currFnc, lastFunctions[1][endStepState]) ? "" : "not ") + "equals to [1]:" + lastFunctions[1][endStepState]); - } } while (consecutiveNullSteps < stepStates.length && !checkEquals(currFnc, lastFunctions[0][endStepState]) && !checkEquals(currFnc, lastFunctions[1][endStepState])); - if (consecutiveNullSteps >= stepStates.length) { + if (consecutiveNullSteps >= stepStates.length) Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", "Loop ended because " + consecutiveNullSteps + " >= " + stepStates.length); - } else if (checkEquals(currFnc, lastFunctions[0][endStepState])) { + else if (checkEquals(currFnc, lastFunctions[0][endStepState])) Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", "Loop ended because " + currFnc + " is equals to [0]:" + lastFunctions[0][endStepState]); - } else { + else Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", "Loop ended because " + currFnc + " is equals to [1]:" + lastFunctions[1][endStepState]); - } return steps; } - private boolean checkEquals(ObjectArrayList a, ObjectArrayList b) { - if (a == null && b == null) { + private boolean checkEquals(final ObjectArrayList a, final ObjectArrayList b) { + if (a == null && b == null) return true; - } else if (a != null && b != null) { + else if (a != null && b != null) if (a.isEmpty() == b.isEmpty()) { int size; if ((size = a.size()) == b.size()) { - for (int i = 0; i < size; i++) { - if (a.get(i).equals(b.get(i)) == false) { + for (int i = 0; i < size; i++) + if (a.get(i).equals(b.get(i)) == false) return false; - } - } return true; } } - } return false; } @SuppressWarnings("unused") - private ObjectArrayList solveStep(ObjectArrayList fncs) throws InterruptedException, Error { + private ObjectArrayList solveStep(final ObjectArrayList fncs) + throws InterruptedException, Error { return solveStep(fncs, stepState); } - private ObjectArrayList solveStep(ObjectArrayList fncs, AtomicInteger stepState) + private ObjectArrayList solveStep(ObjectArrayList fncs, final AtomicInteger stepState) throws InterruptedException, Error { final ObjectArrayList processedFncs = applyRules(fncs, RuleType.EXISTENCE); // Apply existence rules before everything - if (processedFncs != null) { + if (processedFncs != null) fncs = processedFncs; - } RuleType currentAcceptedRules; switch (stepStates[stepState.get()]) { case _1_CALCULATION: { @@ -205,19 +194,18 @@ public class MathSolver { return null; } - private ObjectArrayList applyRules(ObjectArrayList fncs, RuleType currentAcceptedRules) - throws InterruptedException, Error { + private ObjectArrayList applyRules(final ObjectArrayList fncs, + final RuleType currentAcceptedRules) throws InterruptedException, Error { final ObjectArrayList rules = initialFunction.getMathContext().getAcceptableRules(currentAcceptedRules); ObjectArrayList results = null; - ObjectArrayList appliedRules = new ObjectArrayList<>(); + final ObjectArrayList appliedRules = new ObjectArrayList<>(); for (final Function fnc : fncs) { boolean didSomething = false; for (final Rule rule : rules) { - List ruleResults = fnc.simplify(rule); - if ((ruleResults != null && !ruleResults.isEmpty())) { - if (results == null) { + final List ruleResults = fnc.simplify(rule); + if (ruleResults != null && !ruleResults.isEmpty()) { + if (results == null) results = new ObjectArrayList<>(); - } results.addAll(ruleResults); appliedRules.add(rule); didSomething = true; @@ -225,23 +213,21 @@ public class MathSolver { } } if (!didSomething && fncs.size() > 1) { - if (results == null) { + if (results == null) results = new ObjectArrayList<>(); - } results.add(fnc); } } if (appliedRules.isEmpty()) results = null; - if ((Engine.getPlatform().getConsoleUtils().getOutputLevel() >= ConsoleUtils.OUTPUTLEVEL_DEBUG_MIN) & results != null && !appliedRules.isEmpty()) { - StringBuilder rulesStr = new StringBuilder(); - for (Rule r : appliedRules) { + if (Engine.getPlatform().getConsoleUtils().getOutputLevel() >= ConsoleUtils.OUTPUTLEVEL_DEBUG_MIN & results != null && !appliedRules.isEmpty()) { + final StringBuilder rulesStr = new StringBuilder(); + for (final Rule r : appliedRules) { rulesStr.append(r.getRuleName()); rulesStr.append(','); } - if (rulesStr.length() > 0) { + if (rulesStr.length() > 0) rulesStr.setLength(rulesStr.length() - 1); - } Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_VERBOSE, "Math Solver", currentAcceptedRules.toString(), "Applied rules: " + rulesStr); } return results; diff --git a/core/src/main/java/it/cavallium/warppi/math/solver/SolveMethod.java b/core/src/main/java/it/cavallium/warppi/math/solver/SolveMethod.java index 987ea933..5b3b3cdc 100644 --- a/core/src/main/java/it/cavallium/warppi/math/solver/SolveMethod.java +++ b/core/src/main/java/it/cavallium/warppi/math/solver/SolveMethod.java @@ -4,7 +4,7 @@ import it.cavallium.warppi.math.functions.equations.Equation; import it.unimi.dsi.fastutil.objects.ObjectArrayList; public interface SolveMethod { - public static final SolveMethod[] techniques = new SolveMethod[] {}; + SolveMethod[] techniques = new SolveMethod[] {}; - public abstract ObjectArrayList solve(Equation equation); + ObjectArrayList solve(Equation equation); } diff --git a/core/src/main/java/it/cavallium/warppi/util/CacheUtils.java b/core/src/main/java/it/cavallium/warppi/util/CacheUtils.java index 9628004c..b36746bf 100644 --- a/core/src/main/java/it/cavallium/warppi/util/CacheUtils.java +++ b/core/src/main/java/it/cavallium/warppi/util/CacheUtils.java @@ -11,29 +11,28 @@ public class CacheUtils { private static final Map time = Collections.synchronizedMap(new HashMap<>()); @SuppressWarnings("unchecked") - public static T get(String entryName, long expireDelta, Supplier function) { - refreshEntry(entryName); - synchronized (cache) { - if (cache.containsKey(entryName)) { - return (T) cache.get(entryName); - } else { - time.put(entryName, System.currentTimeMillis() + expireDelta); - T result = function.get(); - cache.put(entryName, result); + public static T get(final String entryName, final long expireDelta, final Supplier function) { + CacheUtils.refreshEntry(entryName); + synchronized (CacheUtils.cache) { + if (CacheUtils.cache.containsKey(entryName)) + return (T) CacheUtils.cache.get(entryName); + else { + CacheUtils.time.put(entryName, System.currentTimeMillis() + expireDelta); + final T result = function.get(); + CacheUtils.cache.put(entryName, result); return result; } } } - private static void refreshEntry(String entryName) { - synchronized (time) { - synchronized (cache) { - if (time.containsKey(entryName)) { - if (time.get(entryName) <= System.currentTimeMillis()) { - time.remove(entryName); - cache.remove(entryName); + private static void refreshEntry(final String entryName) { + synchronized (CacheUtils.time) { + synchronized (CacheUtils.cache) { + if (CacheUtils.time.containsKey(entryName)) + if (CacheUtils.time.get(entryName) <= System.currentTimeMillis()) { + CacheUtils.time.remove(entryName); + CacheUtils.cache.remove(entryName); } - } } } } diff --git a/core/src/main/java/it/cavallium/warppi/util/Error.java b/core/src/main/java/it/cavallium/warppi/util/Error.java index 764e62fb..0fd7a345 100644 --- a/core/src/main/java/it/cavallium/warppi/util/Error.java +++ b/core/src/main/java/it/cavallium/warppi/util/Error.java @@ -3,16 +3,16 @@ package it.cavallium.warppi.util; public class Error extends java.lang.Throwable { /** - * + * */ private static final long serialVersionUID = -1014947815755694651L; - public Error(Errors errorID) { + public Error(final Errors errorID) { super(errorID.toString()); id = errorID; } - public Error(Errors errorID, String errorMessage) { + public Error(final Errors errorID, final String errorMessage) { super(errorID.toString() + ": " + errorMessage); id = errorID; } diff --git a/core/src/main/java/it/cavallium/warppi/util/IntWrapper.java b/core/src/main/java/it/cavallium/warppi/util/IntWrapper.java index c8b183c7..fb3c383d 100644 --- a/core/src/main/java/it/cavallium/warppi/util/IntWrapper.java +++ b/core/src/main/java/it/cavallium/warppi/util/IntWrapper.java @@ -3,7 +3,7 @@ package it.cavallium.warppi.util; public class IntWrapper { public int i; - public IntWrapper(int i) { + public IntWrapper(final int i) { this.i = i; } } diff --git a/core/src/main/java/it/cavallium/warppi/util/ScriptUtils.java b/core/src/main/java/it/cavallium/warppi/util/ScriptUtils.java index 0006ab9e..3ea3ac2e 100644 --- a/core/src/main/java/it/cavallium/warppi/util/ScriptUtils.java +++ b/core/src/main/java/it/cavallium/warppi/util/ScriptUtils.java @@ -5,11 +5,12 @@ import java.util.Iterator; import java.util.LinkedList; public class ScriptUtils { - public static boolean instanceOf(Object a, Class b) { + public static boolean instanceOf(final Object a, final Class b) { return b.isInstance(a); } - public static LinkedList mcm(LinkedList factors1, LinkedList factors2) { + public static LinkedList mcm(final LinkedList factors1, + final LinkedList factors2) { final LinkedList mcm = new LinkedList<>(); final Iterator i1 = factors1.iterator(); while (i1.hasNext()) { diff --git a/core/src/main/java/it/cavallium/warppi/util/Utils.java b/core/src/main/java/it/cavallium/warppi/util/Utils.java index 075e2b9d..097274f4 100644 --- a/core/src/main/java/it/cavallium/warppi/util/Utils.java +++ b/core/src/main/java/it/cavallium/warppi/util/Utils.java @@ -50,75 +50,64 @@ public class Utils { public static boolean newtMode = true; - public static boolean isInArray(T ch, T[] a) { + public static boolean isInArray(final T ch, final T[] a) { return Arrays.stream(a).anyMatch(item -> ch.equals(item)); } - public static boolean isInArray(char ch, char[] a) { - for (final char c : a) { + public static boolean isInArray(final char ch, final char[] a) { + for (final char c : a) if (c == ch) return true; - } return false; } private static final String[] regexNormalSymbols = new String[] { "\\", ".", "[", "]", "{", "}", "(", ")", "*", "+", "-", "?", "^", "$", "|" }; - public static String ArrayToRegex(String[] array) { + public static String ArrayToRegex(final String[] array) { String regex = null; for (final String symbol : array) { boolean contained = false; - for (final String smb : regexNormalSymbols) { + for (final String smb : Utils.regexNormalSymbols) if (smb.equals(symbol)) { contained = true; break; } - } if (contained) { - if (regex != null) { + if (regex != null) regex += "|\\" + symbol; - } else { + else regex = "\\" + symbol; - } - } else { - if (regex != null) { - regex += "|" + symbol; - } else { - regex = symbol; - } - } + } else if (regex != null) + regex += "|" + symbol; + else + regex = symbol; } return regex; } - public static String ArrayToRegex(char[] array) { + public static String ArrayToRegex(final char[] array) { String regex = null; for (final char symbol : array) { boolean contained = false; - for (final String smb : regexNormalSymbols) { - if ((smb).equals(symbol + "")) { + for (final String smb : Utils.regexNormalSymbols) + if (smb.equals(symbol + "")) { contained = true; break; } - } if (contained) { - if (regex != null) { + if (regex != null) regex += "|\\" + symbol; - } else { + else regex = "\\" + symbol; - } - } else { - if (regex != null) { - regex += "|" + symbol; - } else { - regex = symbol + ""; - } - } + } else if (regex != null) + regex += "|" + symbol; + else + regex = symbol + ""; } return regex; } - public static String[] concat(String[] a, String[] b) { + public static String[] concat(final String[] a, final String[] b) { final int aLen = a.length; final int bLen = b.length; final String[] c = new String[aLen + bLen]; @@ -127,7 +116,7 @@ public class Utils { return c; } - public static char[] concat(char[] a, char[] b) { + public static char[] concat(final char[] a, final char[] b) { final int aLen = a.length; final int bLen = b.length; final char[] c = new char[aLen + bLen]; @@ -136,7 +125,7 @@ public class Utils { return c; } - public static String[] add(String[] a, String b) { + public static String[] add(final String[] a, final String b) { final int aLen = a.length; final String[] c = new String[aLen + 1]; System.arraycopy(a, 0, c, 0, aLen); @@ -144,7 +133,7 @@ public class Utils { return c; } - public static char[] add(char[] a, char b) { + public static char[] add(final char[] a, final char b) { final int aLen = a.length; final char[] c = new char[aLen + 1]; System.arraycopy(a, 0, c, 0, aLen); @@ -152,159 +141,119 @@ public class Utils { return c; } - public static boolean areThereOnlySettedUpFunctionsSumsEquationsAndSystems(List fl) { - for (int i = 0; i < fl.size(); i++) { - if (!(fl.get(i) instanceof Number || fl.get(i) instanceof Variable || fl.get(i) instanceof Sum || fl.get(i) instanceof SumSubtraction || fl.get(i) instanceof Subtraction || fl.get(i) instanceof Equation || fl.get(i) instanceof EquationsSystemPart || fl.get(i) instanceof Expression)) { + public static boolean areThereOnlySettedUpFunctionsSumsEquationsAndSystems(final List fl) { + for (int i = 0; i < fl.size(); i++) + if (!(fl.get(i) instanceof Number || fl.get(i) instanceof Variable || fl.get(i) instanceof Sum || fl.get(i) instanceof SumSubtraction || fl.get(i) instanceof Subtraction || fl.get(i) instanceof Equation || fl.get(i) instanceof EquationsSystemPart || fl.get(i) instanceof Expression)) if (fl.get(i) instanceof FunctionSingle) { - if (((FunctionSingle) fl.get(i)).getParameter() == null) { + if (((FunctionSingle) fl.get(i)).getParameter() == null) return false; - } } else if (fl.get(i) instanceof FunctionOperator) { - if (((FunctionOperator) fl.get(i)).getParameter1() == null || ((FunctionOperator) fl.get(i)).getParameter2() == null) { + if (((FunctionOperator) fl.get(i)).getParameter1() == null || ((FunctionOperator) fl.get(i)).getParameter2() == null) return false; - } - } else { + } else return false; - } - } - } return true; } - public static boolean areThereOnlySettedUpFunctionsSumsMultiplicationsEquationsAndSystems(List fl) { - for (int i = 0; i < fl.size(); i++) { - if (!(fl.get(i) instanceof Number || fl.get(i) instanceof Variable || fl.get(i) instanceof Multiplication || fl.get(i) instanceof Sum || fl.get(i) instanceof SumSubtraction || fl.get(i) instanceof Subtraction || fl.get(i) instanceof Equation || fl.get(i) instanceof EquationsSystemPart || fl.get(i) instanceof Expression)) { + public static boolean areThereOnlySettedUpFunctionsSumsMultiplicationsEquationsAndSystems(final List fl) { + for (int i = 0; i < fl.size(); i++) + if (!(fl.get(i) instanceof Number || fl.get(i) instanceof Variable || fl.get(i) instanceof Multiplication || fl.get(i) instanceof Sum || fl.get(i) instanceof SumSubtraction || fl.get(i) instanceof Subtraction || fl.get(i) instanceof Equation || fl.get(i) instanceof EquationsSystemPart || fl.get(i) instanceof Expression)) if (fl.get(i) instanceof FunctionSingle) { - if (((FunctionSingle) fl.get(i)).getParameter() == null) { + if (((FunctionSingle) fl.get(i)).getParameter() == null) return false; - } } else if (fl.get(i) instanceof FunctionOperator) { - if (((FunctionOperator) fl.get(i)).getParameter1() == null || ((FunctionOperator) fl.get(i)).getParameter2() == null) { + if (((FunctionOperator) fl.get(i)).getParameter1() == null || ((FunctionOperator) fl.get(i)).getParameter2() == null) return false; - } - } else { + } else return false; - } - } - } return true; } - public static boolean areThereOnlySettedUpFunctionsEquationsAndSystems(List fl) { - for (int i = 0; i < fl.size(); i++) { - if (!(fl.get(i) instanceof Number || fl.get(i) instanceof Variable || fl.get(i) instanceof Equation || fl.get(i) instanceof EquationsSystemPart || fl.get(i) instanceof Expression)) { + public static boolean areThereOnlySettedUpFunctionsEquationsAndSystems(final List fl) { + for (int i = 0; i < fl.size(); i++) + if (!(fl.get(i) instanceof Number || fl.get(i) instanceof Variable || fl.get(i) instanceof Equation || fl.get(i) instanceof EquationsSystemPart || fl.get(i) instanceof Expression)) if (fl.get(i) instanceof FunctionSingle) { - if (((FunctionSingle) fl.get(i)).getParameter() == null) { + if (((FunctionSingle) fl.get(i)).getParameter() == null) return false; - } } else if (fl.get(i) instanceof FunctionOperator) { - if (((FunctionOperator) fl.get(i)).getParameter1() == null || ((FunctionOperator) fl.get(i)).getParameter2() == null) { + if (((FunctionOperator) fl.get(i)).getParameter1() == null || ((FunctionOperator) fl.get(i)).getParameter2() == null) return false; - } - } else { + } else return false; - } - } - } return true; } - public static boolean areThereOnlySettedUpFunctionsAndSystems(List fl) { - for (int i = 0; i < fl.size(); i++) { - if (!(fl.get(i) instanceof Number || fl.get(i) instanceof Variable || fl.get(i) instanceof Equation || fl.get(i) instanceof EquationsSystemPart || fl.get(i) instanceof Expression)) { + public static boolean areThereOnlySettedUpFunctionsAndSystems(final List fl) { + for (int i = 0; i < fl.size(); i++) + if (!(fl.get(i) instanceof Number || fl.get(i) instanceof Variable || fl.get(i) instanceof Equation || fl.get(i) instanceof EquationsSystemPart || fl.get(i) instanceof Expression)) if (fl.get(i) instanceof FunctionSingle) { - if (((FunctionSingle) fl.get(i)).getParameter() == null) { + if (((FunctionSingle) fl.get(i)).getParameter() == null) return false; - } } else if (fl.get(i) instanceof FunctionOperator) { - if (((FunctionOperator) fl.get(i)).getParameter1() == null || ((FunctionOperator) fl.get(i)).getParameter2() == null) { + if (((FunctionOperator) fl.get(i)).getParameter1() == null || ((FunctionOperator) fl.get(i)).getParameter2() == null) return false; - } - } else { + } else return false; - } - } - } return true; } - public static boolean areThereOnlyEmptySNFunctions(List fl) { - for (int i = 0; i < fl.size(); i++) { - if (fl.get(i) instanceof FunctionSingle) { - if (((FunctionSingle) fl.get(i)).getParameter() == null) { + public static boolean areThereOnlyEmptySNFunctions(final List fl) { + for (int i = 0; i < fl.size(); i++) + if (fl.get(i) instanceof FunctionSingle) + if (((FunctionSingle) fl.get(i)).getParameter() == null) return true; - } - } - } return false; } - public static boolean areThereOnlyEmptyNSNFunctions(List fl) { - for (int i = 0; i < fl.size(); i++) { - if (fl.get(i) instanceof FunctionOperator && !(fl.get(i) instanceof Sum) && !(fl.get(i) instanceof SumSubtraction) && !(fl.get(i) instanceof Subtraction) && !(fl.get(i) instanceof Multiplication) && !(fl.get(i) instanceof Division)) { - if (((FunctionOperator) fl.get(i)).getParameter1() == null && ((FunctionOperator) fl.get(i)).getParameter2() == null) { + public static boolean areThereOnlyEmptyNSNFunctions(final List fl) { + for (int i = 0; i < fl.size(); i++) + if (fl.get(i) instanceof FunctionOperator && !(fl.get(i) instanceof Sum) && !(fl.get(i) instanceof SumSubtraction) && !(fl.get(i) instanceof Subtraction) && !(fl.get(i) instanceof Multiplication) && !(fl.get(i) instanceof Division)) + if (((FunctionOperator) fl.get(i)).getParameter1() == null && ((FunctionOperator) fl.get(i)).getParameter2() == null) return true; - } - } - } return false; } - public static boolean areThereEmptyMultiplications(List fl) { - for (int i = 0; i < fl.size(); i++) { - if (fl.get(i) instanceof Multiplication || fl.get(i) instanceof Division) { - if (((FunctionOperator) fl.get(i)).getParameter1() == null && ((FunctionOperator) fl.get(i)).getParameter2() == null) { + public static boolean areThereEmptyMultiplications(final List fl) { + for (int i = 0; i < fl.size(); i++) + if (fl.get(i) instanceof Multiplication || fl.get(i) instanceof Division) + if (((FunctionOperator) fl.get(i)).getParameter1() == null && ((FunctionOperator) fl.get(i)).getParameter2() == null) return true; - } - } - } return false; } - public static boolean areThereEmptySums(List fl) { - for (int i = 0; i < fl.size(); i++) { - if (fl.get(i) instanceof Sum || fl.get(i) instanceof SumSubtraction || fl.get(i) instanceof Subtraction) { - if (((FunctionOperator) fl.get(i)).getParameter1() == null && ((FunctionOperator) fl.get(i)).getParameter2() == null) { + public static boolean areThereEmptySums(final List fl) { + for (int i = 0; i < fl.size(); i++) + if (fl.get(i) instanceof Sum || fl.get(i) instanceof SumSubtraction || fl.get(i) instanceof Subtraction) + if (((FunctionOperator) fl.get(i)).getParameter1() == null && ((FunctionOperator) fl.get(i)).getParameter2() == null) return true; - } - } - } return false; } - public static boolean areThereEmptySystems(List fl) { - for (int i = 0; i < fl.size(); i++) { - if (fl.get(i) instanceof EquationsSystemPart) { - if (((EquationsSystemPart) fl.get(i)).getParameter() == null) { + public static boolean areThereEmptySystems(final List fl) { + for (int i = 0; i < fl.size(); i++) + if (fl.get(i) instanceof EquationsSystemPart) + if (((EquationsSystemPart) fl.get(i)).getParameter() == null) return true; - } - } - } return false; } - public static boolean areThereOtherSettedUpFunctions(List fl) { - for (int i = 0; i < fl.size(); i++) { - if (!(fl.get(i) instanceof Number || fl.get(i) instanceof Variable || fl.get(i) instanceof Sum || fl.get(i) instanceof SumSubtraction || fl.get(i) instanceof Expression || fl.get(i) instanceof FunctionSingle || fl.get(i) instanceof Multiplication || fl.get(i) instanceof Division)) { + public static boolean areThereOtherSettedUpFunctions(final List fl) { + for (int i = 0; i < fl.size(); i++) + if (!(fl.get(i) instanceof Number || fl.get(i) instanceof Variable || fl.get(i) instanceof Sum || fl.get(i) instanceof SumSubtraction || fl.get(i) instanceof Expression || fl.get(i) instanceof FunctionSingle || fl.get(i) instanceof Multiplication || fl.get(i) instanceof Division)) if (fl.get(i) instanceof FunctionSingle) { - if (((FunctionSingle) fl.get(i)).getParameter() == null) { + if (((FunctionSingle) fl.get(i)).getParameter() == null) return true; - } } else if (fl.get(i) instanceof FunctionOperator) { - if (((FunctionOperator) fl.get(i)).getParameter1() == null || ((FunctionOperator) fl.get(i)).getParameter2() == null) { + if (((FunctionOperator) fl.get(i)).getParameter1() == null || ((FunctionOperator) fl.get(i)).getParameter2() == null) return true; - } - } else { + } else return true; - } - } - } return false; } - public static Rational getRational(BigDecimal str) { + public static Rational getRational(final BigDecimal str) { try { - return getRational(str.toString()); + return Utils.getRational(str.toString()); } catch (final Error e) { //E' IMPOSSIBILE CHE VENGA THROWATO UN ERRORE return new Rational("0"); @@ -316,13 +265,12 @@ public class Utils { return new Rational(str); } catch (final NumberFormatException ex) { if (new BigDecimal(str).compareTo(new BigDecimal(8000.0)) < 0 && new BigDecimal(str).compareTo(new BigDecimal(-8000.0)) > 0) { - if (str.equals("-")) { + if (str.equals("-")) str = "-1"; - } final long bits = Double.doubleToLongBits(Double.parseDouble(str)); final long sign = bits >>> 63; - final long exponent = ((bits >>> 52) ^ (sign << 11)) - 1023; + final long exponent = (bits >>> 52 ^ sign << 11) - 1023; final long fraction = bits << 12; // bits are "reversed" but that's // not a problem @@ -330,19 +278,17 @@ public class Utils { long b = 1L; for (int i = 63; i >= 12; i--) { - a = a * 2 + ((fraction >>> i) & 1); + a = a * 2 + (fraction >>> i & 1); b *= 2; } - if (exponent > 0) { + if (exponent > 0) a *= 1 << exponent; - } else { + else b *= 1 << -exponent; - } - if (sign == 1) { + if (sign == 1) a *= -1; - } if (b == 0) { a = 0; @@ -362,25 +308,23 @@ public class Utils { } } - public static BigDecimal rationalToIrrationalString(Rational r) { + public static BigDecimal rationalToIrrationalString(final Rational r) { return BigDecimalMath.divideRound(new BigDecimal(r.numer()).setScale(Utils.scale, Utils.scaleMode), new BigDecimal(r.denom()).setScale(Utils.scale, Utils.scaleMode)); } - public static boolean equalsVariables(List variables, List variables2) { - if (variables.size() != variables2.size()) { + public static boolean equalsVariables(final List variables, final List variables2) { + if (variables.size() != variables2.size()) return false; - } else { - for (final Variable v : variables) { - if (!variables2.contains(v)) { + else { + for (final Variable v : variables) + if (!variables2.contains(v)) return false; - } - } return true; } } @Deprecated - public static void writeSquareRoot(Function var, int x, int y, boolean small) { + public static void writeSquareRoot(final Function var, final int x, final int y, final boolean small) { // var.setSmall(small); // final int w1 = var.getWidth(); // final int h1 = var.getHeight(); @@ -398,85 +342,74 @@ public class Utils { } public static final int getFontHeight() { - return getFontHeight(false); + return Utils.getFontHeight(false); } - public static final BinaryFont getFont(boolean small) { - return getFont(small, StaticVars.zoomed); + public static final BinaryFont getFont(final boolean small) { + return Utils.getFont(small, StaticVars.zoomed); } - public static final BinaryFont getFont(boolean small, boolean zoomed) { - return Engine.INSTANCE.getHardwareDevice().getDisplayManager().fonts[getFontIndex(small, zoomed)]; + public static final BinaryFont getFont(final boolean small, final boolean zoomed) { + return Engine.INSTANCE.getHardwareDevice().getDisplayManager().fonts[Utils.getFontIndex(small, zoomed)]; } - public static final int getFontIndex(boolean small, boolean zoomed) { + public static final int getFontIndex(final boolean small, final boolean zoomed) { if (small) { - if (zoomed) { + if (zoomed) return 3; - } else { + else return 1; - } - } else { - if (zoomed) { - return 2; - } else { - return 0; - } - } + } else if (zoomed) + return 2; + else + return 0; } - public static final int getFontHeight(boolean small) { - return getFontHeight(small, StaticVars.zoomed); + public static final int getFontHeight(final boolean small) { + return Utils.getFontHeight(small, StaticVars.zoomed); } - public static final int getFontHeight(boolean small, boolean zoomed) { + public static final int getFontHeight(final boolean small, final boolean zoomed) { if (small) { - if (zoomed) { + if (zoomed) return Engine.INSTANCE.getHardwareDevice().getDisplayManager().glyphsHeight[3]; - } else { + else return Engine.INSTANCE.getHardwareDevice().getDisplayManager().glyphsHeight[1]; - } - } else { - if (zoomed) { - return Engine.INSTANCE.getHardwareDevice().getDisplayManager().glyphsHeight[2]; - } else { - return Engine.INSTANCE.getHardwareDevice().getDisplayManager().glyphsHeight[0]; - } - } + } else if (zoomed) + return Engine.INSTANCE.getHardwareDevice().getDisplayManager().glyphsHeight[2]; + else + return Engine.INSTANCE.getHardwareDevice().getDisplayManager().glyphsHeight[0]; } - public static byte[] convertStreamToByteArray(InputStream stream, long size) throws IOException { + public static byte[] convertStreamToByteArray(final InputStream stream, final long size) throws IOException { // check to ensure that file size is not larger than Integer.MAX_VALUE. - if (size > Integer.MAX_VALUE) { + if (size > Integer.MAX_VALUE) return new byte[0]; - } final byte[] buffer = new byte[(int) size]; final ByteArrayOutputStream os = new ByteArrayOutputStream(); int line = 0; // read bytes from stream, and store them in buffer - while ((line = stream.read(buffer)) != -1) { + while ((line = stream.read(buffer)) != -1) // Writes bytes from byte array (buffer) into output stream. os.write(buffer, 0, line); - } stream.close(); os.flush(); os.close(); return os.toByteArray(); } - public static int[] realBytes(byte[] bytes) { + public static int[] realBytes(final byte[] bytes) { final int len = bytes.length; final int[] realbytes = new int[len]; - for (int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) realbytes[i] = bytes[i] & 0xFF; - } return realbytes; } - public static Function[][] joinFunctionsResults(List l1, List l2) { + public static Function[][] joinFunctionsResults(final List l1, final List l2) { final int size1 = l1.size(); final int size2 = l2.size(); int cur1 = 0; @@ -485,95 +418,77 @@ public class Utils { final Function[][] results = new Function[total][2]; for (int i = 0; i < total; i++) { results[i] = new Function[] { l1.get(cur1), l2.get(cur2) }; - if (i % size2 == 0) { + if (i % size2 == 0) cur1 += 1; - } - if (i % size1 == 0) { + if (i % size1 == 0) cur2 += 1; - } - if (cur1 >= size1) { + if (cur1 >= size1) cur1 = 0; - } - if (cur2 >= size2) { + if (cur2 >= size2) cur2 = 0; - } } return results; } - public static Function[][] joinFunctionsResults(ObjectArrayList> ln) { + public static Function[][] joinFunctionsResults(final ObjectArrayList> ln) { final int[] sizes = new int[ln.size()]; - for (int i = 0; i < ln.size(); i++) { + for (int i = 0; i < ln.size(); i++) sizes[i] = ln.get(i).size(); - } final int[] curs = new int[sizes.length]; int total = 0; - for (int i = 0; i < ln.size(); i++) { - if (i == 0) { + for (int i = 0; i < ln.size(); i++) + if (i == 0) total = sizes[i]; - } else { + else total *= sizes[i]; - } - } final Function[][] results = new Function[total][sizes.length]; for (int i = 0; i < total; i++) { results[i] = new Function[sizes.length]; - for (int j = 0; j < sizes.length; j++) { + for (int j = 0; j < sizes.length; j++) results[i][j] = ln.get(j).get(curs[j]); - } - for (int k = 0; k < sizes.length; k++) { - if (i % sizes[k] == 0) { - for (int l = 0; l < sizes.length; l++) { - if (l != k) { + for (int k = 0; k < sizes.length; k++) + if (i % sizes[k] == 0) + for (int l = 0; l < sizes.length; l++) + if (l != k) curs[l] += 1; - } - } - } - } - for (int k = 0; k < sizes.length; k++) { - if (curs[k] >= sizes[k]) { + for (int k = 0; k < sizes.length; k++) + if (curs[k] >= sizes[k]) curs[k] = 0; - } - } } return results; } - public static boolean isNegative(Function b) { - if (b instanceof Negative) { + public static boolean isNegative(final Function b) { + if (b instanceof Negative) return true; - } else if (b instanceof Number && ((Number) b).getTerm().compareTo(BigDecimal.ZERO) < 0) { + else if (b instanceof Number && ((Number) b).getTerm().compareTo(BigDecimal.ZERO) < 0) return true; - } return false; } - public static CharSequence multipleChars(String string, int i) { + public static CharSequence multipleChars(final String string, final int i) { String result = ""; - for (int j = 0; j < i; j++) { + for (int j = 0; j < i; j++) result += string; - } return result; } - public static boolean isIntegerValue(BigDecimal bd) { + public static boolean isIntegerValue(final BigDecimal bd) { return bd.signum() == 0 || bd.scale() <= 0 || bd.stripTrailingZeros().scale() <= 0; } @SafeVarargs - public static String arrayToString(T... data) { + public static String arrayToString(final T... data) { String sdata = ""; - for (final T o : data) { + for (final T o : data) sdata += "," + o; - } return sdata.substring(1); } - public static String arrayToString(boolean... data) { + public static String arrayToString(final boolean... data) { String sdata = ""; - for (final boolean o : data) { - sdata += (o) ? 1 : 0; - } + for (final boolean o : data) + sdata += o ? 1 : 0; return sdata; } @@ -593,50 +508,46 @@ public class Utils { boolean mb = false; final String displayName = method.getName(); final String displayValue = value.toString(); - if (displayName.endsWith("CpuLoad")) { + if (displayName.endsWith("CpuLoad")) percent = true; - } - if (displayName.endsWith("MemorySize")) { + if (displayName.endsWith("MemorySize")) mb = true; - } final List arr = new ArrayList<>(); arr.add("getFreePhysicalMemorySize"); arr.add("getProcessCpuLoad"); arr.add("getSystemCpuLoad"); arr.add("getTotalPhysicalMemorySize"); - if (arr.contains(displayName)) { - if (percent) { + if (arr.contains(displayName)) + if (percent) try { - System.out.println(displayName + " = " + (((int) (Float.parseFloat(displayValue) * 10000f)) / 100f) + "%"); + System.out.println(displayName + " = " + (int) (Float.parseFloat(displayValue) * 10000f) / 100f + "%"); } catch (final Exception ex) { System.out.println(displayName + " = " + displayValue); } - } else if (mb) { + else if (mb) try { - System.out.println(displayName + " = " + (Long.parseLong(displayValue) / 1024L / 1024L) + " MB"); + System.out.println(displayName + " = " + Long.parseLong(displayValue) / 1024L / 1024L + " MB"); } catch (final Exception ex) { System.out.println(displayName + " = " + displayValue); } - } else { + else System.out.println(displayName + " = " + displayValue); - } - } } // if } // for System.out.println("============"); } public static boolean isWindows() { - return (Engine.getPlatform().getOsName().indexOf("win") >= 0); + return Engine.getPlatform().getOsName().indexOf("win") >= 0; } - public static ObjectArrayList newArrayList(T o) { + public static ObjectArrayList newArrayList(final T o) { final ObjectArrayList t = new ObjectArrayList<>(); t.add(o); return t; } - public static InputStream getResourceStreamSafe(String string) throws IOException, URISyntaxException { + public static InputStream getResourceStreamSafe(final String string) throws IOException, URISyntaxException { try { return Engine.getPlatform().getStorageUtils().getResourceStream(string); } catch (final Exception ex) { @@ -648,11 +559,10 @@ public class Utils { return new File("").getAbsoluteFile(); } - public static U getOrDefault(Map enginesList, T key, U object) { - if (enginesList.containsKey(key)) { + public static U getOrDefault(final Map enginesList, final T key, final U object) { + if (enginesList.containsKey(key)) return enginesList.get(key); - } else { + else return object; - } } } diff --git a/core/src/main/java/org/nevec/rjm/Bernoulli.java b/core/src/main/java/org/nevec/rjm/Bernoulli.java index a313b36f..78b2fc65 100644 --- a/core/src/main/java/org/nevec/rjm/Bernoulli.java +++ b/core/src/main/java/org/nevec/rjm/Bernoulli.java @@ -7,7 +7,7 @@ import it.cavallium.warppi.util.Error; /** * Bernoulli numbers. - * + * * @since 2006-06-25 * @author Richard J. Mathar */ @@ -18,15 +18,15 @@ public class Bernoulli { static Vector a = new Vector<>(); public Bernoulli() { - if (a.size() == 0) { - a.add(Rational.ONE); - a.add(new Rational(1, 6)); + if (Bernoulli.a.size() == 0) { + Bernoulli.a.add(Rational.ONE); + Bernoulli.a.add(new Rational(1, 6)); } } /** * Set a coefficient in the internal table. - * + * * @param n * the zero-based index of the coefficient. n=0 for the constant * term. @@ -35,59 +35,55 @@ public class Bernoulli { */ protected void set(final int n, final Rational value) { final int nindx = n / 2; - if (nindx < a.size()) { - a.set(nindx, value); - } else { - while (a.size() < nindx) { - a.add(Rational.ZERO); - } - a.add(value); + if (nindx < Bernoulli.a.size()) + Bernoulli.a.set(nindx, value); + else { + while (Bernoulli.a.size() < nindx) + Bernoulli.a.add(Rational.ZERO); + Bernoulli.a.add(value); } } /** * The Bernoulli number at the index provided. - * + * * @param n * the index, non-negative. * @return the B_0=1 for n=0, B_1=-1/2 for n=1, B_2=1/6 for n=2 etc * @throws Error */ - public Rational at(int n) throws Error { - if (n == 1) { - return (new Rational(-1, 2)); - } else if (n % 2 != 0) { + public Rational at(final int n) throws Error { + if (n == 1) + return new Rational(-1, 2); + else if (n % 2 != 0) return Rational.ZERO; - } else { + else { final int nindx = n / 2; - if (a.size() <= nindx) { - for (int i = 2 * a.size(); i <= n; i += 2) { + if (Bernoulli.a.size() <= nindx) + for (int i = 2 * Bernoulli.a.size(); i <= n; i += 2) set(i, doubleSum(i)); - } - } - return a.elementAt(nindx); + return Bernoulli.a.elementAt(nindx); } } /* * Generate a new B_n by a standard double sum. - * + * * @param n The index of the Bernoulli number. - * + * * @return The Bernoulli number at n. */ - private Rational doubleSum(int n) throws Error { + private Rational doubleSum(final int n) throws Error { Rational resul = Rational.ZERO; for (int k = 0; k <= n; k++) { Rational jsum = Rational.ZERO; BigInteger bin = BigInteger.ONE; for (int j = 0; j <= k; j++) { - final BigInteger jpown = (new BigInteger("" + j)).pow(n); - if (j % 2 == 0) { + final BigInteger jpown = new BigInteger("" + j).pow(n); + if (j % 2 == 0) jsum = jsum.add(bin.multiply(jpown)); - } else { + else jsum = jsum.subtract(bin.multiply(jpown)); - } /* * update binomial(k,j) recursively diff --git a/core/src/main/java/org/nevec/rjm/BigComplex.java b/core/src/main/java/org/nevec/rjm/BigComplex.java index 67751010..badf5482 100644 --- a/core/src/main/java/org/nevec/rjm/BigComplex.java +++ b/core/src/main/java/org/nevec/rjm/BigComplex.java @@ -5,7 +5,7 @@ import java.math.MathContext; /** * Complex numbers with BigDecimal real and imaginary components - * + * * @since 2008-10-26 * @author Richard J. Mathar */ @@ -35,45 +35,45 @@ public class BigComplex { /** * ctor with real and imaginary parts - * + * * @param x * real part * @param y * imaginary part */ - public BigComplex(BigDecimal x, BigDecimal y) { + public BigComplex(final BigDecimal x, final BigDecimal y) { re = x; im = y; } /** * ctor with real part. - * + * * @param x * real part. * The imaginary part is set to zero. */ - public BigComplex(BigDecimal x) { + public BigComplex(final BigDecimal x) { re = x; im = BigDecimal.ZERO; } /** * ctor with real and imaginary parts - * + * * @param x * real part * @param y * imaginary part */ - public BigComplex(double x, double y) { + public BigComplex(final double x, final double y) { re = new BigDecimal(x); im = new BigDecimal(y); } /** * Multiply with another BigComplex - * + * * @param oth * The BigComplex which is a factor in the product * @param mc @@ -82,7 +82,7 @@ public class BigComplex { * @since 2010-07-19 implemented with 3 multiplications and 5 * additions/subtractions */ - BigComplex multiply(final BigComplex oth, MathContext mc) { + BigComplex multiply(final BigComplex oth, final MathContext mc) { final BigDecimal a = re.add(im).multiply(oth.re); final BigDecimal b = oth.re.add(oth.im).multiply(im); final BigDecimal c = oth.im.subtract(oth.re).multiply(re); @@ -93,7 +93,7 @@ public class BigComplex { /** * Add a BigDecimal - * + * * @param oth * the value to be added to the real part. * @return this added to oth @@ -105,7 +105,7 @@ public class BigComplex { /** * Subtract another BigComplex - * + * * @param oth * the value to be subtracted from this. * @return this minus oth @@ -118,7 +118,7 @@ public class BigComplex { /** * Complex-conjugation - * + * * @return the complex conjugate of this. */ BigComplex conj() { @@ -127,7 +127,7 @@ public class BigComplex { /** * The absolute value squared. - * + * * @return The sum of the squares of real and imaginary parts. * This is the square of BigComplex.abs() . */ @@ -137,18 +137,18 @@ public class BigComplex { /** * The absolute value. - * + * * @return the square root of the sum of the squares of real and imaginary * parts. * @since 2008-10-27 */ - BigDecimal abs(MathContext mc) { + BigDecimal abs(final MathContext mc) { return BigDecimalMath.sqrt(norm(), mc); } /** * The square root. - * + * * @return the square root of the this. * The branch is chosen such that the imaginary part of the result * has the @@ -158,31 +158,29 @@ public class BigComplex { * ISSAC 1996 p142-149. * @since 2008-10-27 */ - BigComplex sqrt(MathContext mc) { + BigComplex sqrt(final MathContext mc) { final BigDecimal half = new BigDecimal("2"); /* * compute l=sqrt(re^2+im^2), then u=sqrt((l+re)/2) * and v= +- sqrt((l-re)/2 as the new real and imaginary parts. */ final BigDecimal l = abs(mc); - if (l.compareTo(BigDecimal.ZERO) == 0) { + if (l.compareTo(BigDecimal.ZERO) == 0) return new BigComplex(BigDecimalMath.scalePrec(BigDecimal.ZERO, mc), BigDecimalMath.scalePrec(BigDecimal.ZERO, mc)); - } final BigDecimal u = BigDecimalMath.sqrt(l.add(re).divide(half, mc), mc); final BigDecimal v = BigDecimalMath.sqrt(l.subtract(re).divide(half, mc), mc); - if (im.compareTo(BigDecimal.ZERO) >= 0) { + if (im.compareTo(BigDecimal.ZERO) >= 0) return new BigComplex(u, v); - } else { + else return new BigComplex(u, v.negate()); - } } /** * The inverse of this. - * + * * @return 1/this */ - BigComplex inverse(MathContext mc) { + BigComplex inverse(final MathContext mc) { final BigDecimal hyp = norm(); /* 1/(x+iy)= (x-iy)/(x^2+y^2 */ return new BigComplex(re.divide(hyp, mc), im.divide(hyp, mc).negate()); @@ -190,17 +188,17 @@ public class BigComplex { /** * Divide through another BigComplex number. - * + * * @return this/oth */ - BigComplex divide(BigComplex oth, MathContext mc) { + BigComplex divide(final BigComplex oth, final MathContext mc) { /* lazy implementation: (x+iy)/(a+ib)= (x+iy)* 1/(a+ib) */ return multiply(oth.inverse(mc), mc); } /** * Human-readable Fortran-type display - * + * * @return real and imaginary part in parenthesis, divided by a comma. */ @Override @@ -210,10 +208,10 @@ public class BigComplex { /** * Human-readable Fortran-type display - * + * * @return real and imaginary part in parenthesis, divided by a comma. */ - public String toString(MathContext mc) { + public String toString(final MathContext mc) { return "(" + re.round(mc).toString() + "," + im.round(mc).toString() + ")"; } diff --git a/core/src/main/java/org/nevec/rjm/BigDecimalMath.java b/core/src/main/java/org/nevec/rjm/BigDecimalMath.java index 8bb91449..82fe43dd 100644 --- a/core/src/main/java/org/nevec/rjm/BigDecimalMath.java +++ b/core/src/main/java/org/nevec/rjm/BigDecimalMath.java @@ -11,7 +11,7 @@ import it.cavallium.warppi.util.Error; * BigDecimal special functions. * A Java Math.BigDecimal * Implementation of Core Mathematical Functions - * + * * @since 2009-05-22 * @author Richard J. Mathar * @see apfloat @@ -51,7 +51,7 @@ public class BigDecimalMath { /** * Euler's constant. - * + * * @param mc * The required precision of the result. * @return 3.14159... @@ -60,34 +60,34 @@ public class BigDecimalMath { */ static public BigDecimal pi(final MathContext mc) throws Error { /* look it up if possible */ - if (mc.getPrecision() < PI.precision()) { - return PI.round(mc); - } else { + if (mc.getPrecision() < BigDecimalMath.PI.precision()) + return BigDecimalMath.PI.round(mc); + else { /* * Broadhurst arXiv:math/9803067 */ final int[] a = { 1, 0, 0, -1, -1, -1, 0, 0 }; - final BigDecimal S = broadhurstBBP(1, 1, a, mc); - return multiplyRound(S, 8); + final BigDecimal S = BigDecimalMath.broadhurstBBP(1, 1, a, mc); + return BigDecimalMath.multiplyRound(S, 8); } } /* BigDecimalMath.pi */ /** * Euler-Mascheroni constant. - * + * * @param mc * The required precision of the result. * @return 0.577... * @throws Error * @since 2009-08-13 */ - static public BigDecimal gamma(MathContext mc) throws Error { + static public BigDecimal gamma(final MathContext mc) throws Error { /* look it up if possible */ - if (mc.getPrecision() < GAMMA.precision()) { - return GAMMA.round(mc); - } else { - final double eps = prec2err(0.577, mc.getPrecision()); + if (mc.getPrecision() < BigDecimalMath.GAMMA.precision()) + return BigDecimalMath.GAMMA.round(mc); + else { + final double eps = BigDecimalMath.prec2err(0.577, mc.getPrecision()); /* * Euler-Stieltjes as shown in Dilcher, Aequat Math 48 (1) (1994) @@ -95,8 +95,8 @@ public class BigDecimalMath { */ MathContext mcloc = SafeMathContext.newMathContext(2 + mc.getPrecision()); BigDecimal resul = BigDecimal.ONE; - resul = resul.add(log(2, mcloc)); - resul = resul.subtract(log(3, mcloc)); + resul = resul.add(BigDecimalMath.log(2, mcloc)); + resul = resul.subtract(BigDecimalMath.log(3, mcloc)); /* * how many terms: zeta-1 falls as 1/2^(2n+1), so the @@ -105,20 +105,19 @@ public class BigDecimalMath { * Log(2) is 0.7 */ final int kmax = (int) ((Math.log(eps / 0.7) - 2.) / 4.); - mcloc = SafeMathContext.newMathContext(1 + err2prec(1.2, eps / kmax)); + mcloc = SafeMathContext.newMathContext(1 + BigDecimalMath.err2prec(1.2, eps / kmax)); for (int n = 1;; n++) { /* * zeta is close to 1. Division of zeta-1 through * 4^n*(2n+1) means divion through roughly 2^(2n+1) */ - BigDecimal c = zeta(2 * n + 1, mcloc).subtract(BigDecimal.ONE); + BigDecimal c = BigDecimalMath.zeta(2 * n + 1, mcloc).subtract(BigDecimal.ONE); BigInteger fourn = new BigInteger("" + (2 * n + 1)); fourn = fourn.shiftLeft(2 * n); - c = divideRound(c, fourn); + c = BigDecimalMath.divideRound(c, fourn); resul = resul.subtract(c); - if (c.doubleValue() < 0.1 * eps) { + if (c.doubleValue() < 0.1 * eps) break; - } } return resul.round(mc); } @@ -127,7 +126,7 @@ public class BigDecimalMath { /** * The square root. - * + * * @param x * the non-negative argument. * @param mc @@ -135,12 +134,10 @@ public class BigDecimalMath { * @since 2008-10-27 */ static public BigDecimal sqrt(final BigDecimal x, final MathContext mc) { - if (x.compareTo(BigDecimal.ZERO) < 0) { + if (x.compareTo(BigDecimal.ZERO) < 0) throw new ArithmeticException("negative argument " + x.toString() + " of square root"); - } - if (x.abs().subtract(new BigDecimal(Math.pow(10., -mc.getPrecision()))).compareTo(BigDecimal.ZERO) < 0) { + if (x.abs().subtract(new BigDecimal(Math.pow(10., -mc.getPrecision()))).compareTo(BigDecimal.ZERO) < 0) return BigDecimalMath.scalePrec(BigDecimal.ZERO, mc); - } /* start the computation from a double precision estimate */ BigDecimal s = new BigDecimal(Math.sqrt(x.doubleValue()), mc); final BigDecimal half = new BigDecimal("2"); @@ -160,9 +157,8 @@ public class BigDecimalMath { * (actually half of this, which we use for a little bit of * additional protection). */ - if (Math.abs(BigDecimal.ONE.subtract(x.divide(s.pow(2, locmc), locmc)).doubleValue()) <= eps) { + if (Math.abs(BigDecimal.ONE.subtract(x.divide(s.pow(2, locmc), locmc)).doubleValue()) <= eps) break; - } s = s.add(x.divide(s, locmc)).divide(half, locmc); /* debugging */ // System.out.println("itr "+x.round(locmc).toString() + " " + @@ -173,7 +169,7 @@ public class BigDecimalMath { /** * The square root. - * + * * @param x * the non-negative argument. * @return the square root of the BigDecimal rounded to the precision @@ -181,16 +177,15 @@ public class BigDecimalMath { * @since 2009-06-25 */ static public BigDecimal sqrt(final BigDecimal x) { - if (x.compareTo(BigDecimal.ZERO) < 0) { + if (x.compareTo(BigDecimal.ZERO) < 0) throw new ArithmeticException("negative argument " + x.toString() + " of square root"); - } - return root(2, x); + return BigDecimalMath.root(2, x); } /* BigDecimalMath.sqrt */ /** * The cube root. - * + * * @param x * The argument. * @return The cubic root of the BigDecimal rounded to the precision implied @@ -199,16 +194,15 @@ public class BigDecimalMath { * @since 2009-08-16 */ static public BigDecimal cbrt(final BigDecimal x) { - if (x.compareTo(BigDecimal.ZERO) < 0) { - return root(3, x.negate()).negate(); - } else { - return root(3, x); - } + if (x.compareTo(BigDecimal.ZERO) < 0) + return BigDecimalMath.root(3, x.negate()).negate(); + else + return BigDecimalMath.root(3, x); } /* BigDecimalMath.cbrt */ /** * The integer root. - * + * * @param n * the positive argument. * @param x @@ -218,16 +212,13 @@ public class BigDecimalMath { * @since 2009-07-30 */ static public BigDecimal root(final int n, final BigDecimal x) { - if (x.compareTo(BigDecimal.ZERO) < 0) { + if (x.compareTo(BigDecimal.ZERO) < 0) throw new ArithmeticException("negative argument " + x.toString() + " of root"); - } - if (n <= 0) { + if (n <= 0) throw new ArithmeticException("negative power " + n + " of root"); - } - if (n == 1) { + if (n == 1) return x; - } /* start the computation from a double precision estimate */ BigDecimal s = new BigDecimal(Math.pow(x.doubleValue(), 1.0 / n)); @@ -241,7 +232,7 @@ public class BigDecimalMath { * Specify an internal accuracy within the loop which is * slightly larger than what is demanded by 'eps' below. */ - final BigDecimal xhighpr = scalePrec(x, 2); + final BigDecimal xhighpr = BigDecimalMath.scalePrec(x, 2); final MathContext mc = SafeMathContext.newMathContext(2 + x.precision()); /* @@ -260,16 +251,15 @@ public class BigDecimalMath { final MathContext locmc = SafeMathContext.newMathContext(c.precision()); c = c.divide(nth, locmc); s = s.subtract(c); - if (Math.abs(c.doubleValue() / s.doubleValue()) < eps) { + if (Math.abs(c.doubleValue() / s.doubleValue()) < eps) break; - } } - return s.round(SafeMathContext.newMathContext(err2prec(eps))); + return s.round(SafeMathContext.newMathContext(BigDecimalMath.err2prec(eps))); } /* BigDecimalMath.root */ /** * The hypotenuse. - * + * * @param x * the first argument. * @param y @@ -291,22 +281,22 @@ public class BigDecimalMath { * digits. */ final BigDecimal zerr = x.abs().multiply(x.ulp()).add(y.abs().multiply(y.ulp())); - MathContext mc = SafeMathContext.newMathContext(2 + err2prec(z, zerr)); + MathContext mc = SafeMathContext.newMathContext(2 + BigDecimalMath.err2prec(z, zerr)); /* Pull square root */ - z = sqrt(z.round(mc)); + z = BigDecimalMath.sqrt(z.round(mc)); /* * Final rounding. Absolute error in the square root is * (y*yerr+x*xerr)/z, where zerr holds 2*(x*xerr+y*yerr). */ - mc = SafeMathContext.newMathContext(err2prec(z.doubleValue(), 0.5 * zerr.doubleValue() / z.doubleValue())); + mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(z.doubleValue(), 0.5 * zerr.doubleValue() / z.doubleValue())); return z.round(mc); } /* BigDecimalMath.hypot */ /** * The hypotenuse. - * + * * @param n * the first argument. * @param x @@ -319,7 +309,7 @@ public class BigDecimalMath { /* * compute n^2+x^2 in infinite precision */ - BigDecimal z = (new BigDecimal(n)).pow(2).add(x.pow(2)); + BigDecimal z = new BigDecimal(n).pow(2).add(x.pow(2)); /* * Truncate to the precision set by x. Absolute error = in z (square of @@ -330,16 +320,16 @@ public class BigDecimalMath { * so this feature does not harm. */ final double zerr = x.doubleValue() * x.ulp().doubleValue(); - MathContext mc = SafeMathContext.newMathContext(2 + err2prec(z.doubleValue(), zerr)); + MathContext mc = SafeMathContext.newMathContext(2 + BigDecimalMath.err2prec(z.doubleValue(), zerr)); /* Pull square root */ - z = sqrt(z.round(mc)); + z = BigDecimalMath.sqrt(z.round(mc)); /* * Final rounding. Absolute error in the square root is x*xerr/z, where * zerr holds 2*x*xerr. */ - mc = SafeMathContext.newMathContext(err2prec(z.doubleValue(), 0.5 * zerr / z.doubleValue())); + mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(z.doubleValue(), 0.5 * zerr / z.doubleValue())); return z.round(mc); } /* BigDecimalMath.hypot */ @@ -351,7 +341,7 @@ public class BigDecimalMath { /** * The exponential function. - * + * * @param x * the argument. * @return exp(x). @@ -364,12 +354,12 @@ public class BigDecimalMath { * @since 2009-05-29 * @author Richard J. Mathar */ - static public BigDecimal exp(BigDecimal x) { + static public BigDecimal exp(final BigDecimal x) { /* * To calculate the value if x is negative, use exp(-x) = 1/exp(x) */ if (x.compareTo(BigDecimal.ZERO) < 0) { - final BigDecimal invx = exp(x.negate()); + final BigDecimal invx = BigDecimalMath.exp(x.negate()); /* * Relative error in inverse of invx is the same as the relative * errror in invx. @@ -377,14 +367,14 @@ public class BigDecimalMath { */ final MathContext mc = SafeMathContext.newMathContext(invx.precision()); return BigDecimal.ONE.divide(invx, mc); - } else if (x.compareTo(BigDecimal.ZERO) == 0) { + } else if (x.compareTo(BigDecimal.ZERO) == 0) /* * recover the valid number of digits from x.ulp(), if x hits the * zero. The x.precision() is 1 then, and does not provide this * information. */ - return scalePrec(BigDecimal.ONE, -(int) (Math.log10(x.ulp().doubleValue()))); - } else { + return BigDecimalMath.scalePrec(BigDecimal.ONE, -(int) Math.log10(x.ulp().doubleValue())); + else { /* * Push the number in the Taylor expansion down to a small * value where TAYLOR_NTERM terms will do. If x<1, the n-th term is @@ -400,7 +390,7 @@ public class BigDecimalMath { */ final double xDbl = x.doubleValue(); final double xUlpDbl = x.ulp().doubleValue(); - if (Math.pow(xDbl, TAYLOR_NTERM) < TAYLOR_NTERM * (TAYLOR_NTERM - 1.0) * (TAYLOR_NTERM - 2.0) * xUlpDbl) { + if (Math.pow(xDbl, BigDecimalMath.TAYLOR_NTERM) < BigDecimalMath.TAYLOR_NTERM * (BigDecimalMath.TAYLOR_NTERM - 1.0) * (BigDecimalMath.TAYLOR_NTERM - 2.0) * xUlpDbl) { /* * Add TAYLOR_NTERM terms of the Taylor expansion (Euler's sum * formula) @@ -420,22 +410,21 @@ public class BigDecimalMath { * add noise beyond * what's already in x. */ - final MathContext mcTay = SafeMathContext.newMathContext(err2prec(1., xUlpDbl / TAYLOR_NTERM)); - for (int i = 1; i <= TAYLOR_NTERM; i++) { + final MathContext mcTay = SafeMathContext.newMathContext(BigDecimalMath.err2prec(1., xUlpDbl / BigDecimalMath.TAYLOR_NTERM)); + for (int i = 1; i <= BigDecimalMath.TAYLOR_NTERM; i++) { ifac = ifac.multiply(new BigInteger("" + i)); xpowi = xpowi.multiply(x); final BigDecimal c = xpowi.divide(new BigDecimal(ifac), mcTay); resul = resul.add(c); - if (Math.abs(xpowi.doubleValue()) < i && Math.abs(c.doubleValue()) < 0.5 * xUlpDbl) { + if (Math.abs(xpowi.doubleValue()) < i && Math.abs(c.doubleValue()) < 0.5 * xUlpDbl) break; - } } /* * exp(x+deltax) = exp(x)(1+deltax) if deltax is <<1. So the * relative error * in the result equals the absolute error in the argument. */ - final MathContext mc = SafeMathContext.newMathContext(err2prec(xUlpDbl / 2.)); + final MathContext mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(xUlpDbl / 2.)); return resul.round(mc); } else { /* @@ -443,9 +432,9 @@ public class BigDecimalMath { * lead * to loss of accuracy. */ - int exSc = (int) (1.0 - Math.log10(TAYLOR_NTERM * (TAYLOR_NTERM - 1.0) * (TAYLOR_NTERM - 2.0) * xUlpDbl / Math.pow(xDbl, TAYLOR_NTERM)) / (TAYLOR_NTERM - 1.0)); + int exSc = (int) (1.0 - Math.log10(BigDecimalMath.TAYLOR_NTERM * (BigDecimalMath.TAYLOR_NTERM - 1.0) * (BigDecimalMath.TAYLOR_NTERM - 2.0) * xUlpDbl / Math.pow(xDbl, BigDecimalMath.TAYLOR_NTERM)) / (BigDecimalMath.TAYLOR_NTERM - 1.0)); final BigDecimal xby10 = x.scaleByPowerOfTen(-exSc); - BigDecimal expxby10 = exp(xby10); + BigDecimal expxby10 = BigDecimalMath.exp(xby10); /* * Final powering by 10 means that the relative error of the @@ -465,9 +454,8 @@ public class BigDecimalMath { exSc -= exsub; final MathContext mctmp = SafeMathContext.newMathContext(expxby10.precision() - exsub + 2); int pex = 1; - while (exsub-- > 0) { + while (exsub-- > 0) pex *= 10; - } expxby10 = expxby10.pow(pex, mctmp); } return expxby10.round(mc); @@ -477,7 +465,7 @@ public class BigDecimalMath { /** * The base of the natural logarithm. - * + * * @param mc * the required precision of the result * @return exp(1) = 2.71828.... @@ -485,21 +473,21 @@ public class BigDecimalMath { */ static public BigDecimal exp(final MathContext mc) { /* look it up if possible */ - if (mc.getPrecision() < E.precision()) { - return E.round(mc); - } else { + if (mc.getPrecision() < BigDecimalMath.E.precision()) + return BigDecimalMath.E.round(mc); + else { /* * Instantiate a 1.0 with the requested pseudo-accuracy * and delegate the computation to the public method above. */ - final BigDecimal uni = scalePrec(BigDecimal.ONE, mc.getPrecision()); - return exp(uni); + final BigDecimal uni = BigDecimalMath.scalePrec(BigDecimal.ONE, mc.getPrecision()); + return BigDecimalMath.exp(uni); } } /* BigDecimalMath.exp */ /** * The natural logarithm. - * + * * @param x * the argument. * @return ln(x). @@ -508,38 +496,36 @@ public class BigDecimalMath { * @since 2009-05-29 * @author Richard J. Mathar */ - static public BigDecimal log(BigDecimal x) { + static public BigDecimal log(final BigDecimal x) { /* * the value is undefined if x is negative. */ - if (x.compareTo(BigDecimal.ZERO) < 0) { + if (x.compareTo(BigDecimal.ZERO) < 0) throw new ArithmeticException("Cannot take log of negative " + x.toString()); - } else if (x.compareTo(BigDecimal.ONE) == 0) { + else if (x.compareTo(BigDecimal.ONE) == 0) /* log 1. = 0. */ - return scalePrec(BigDecimal.ZERO, x.precision() - 1); - } else if (Math.abs(x.doubleValue() - 1.0) <= 0.3) { + return BigDecimalMath.scalePrec(BigDecimal.ZERO, x.precision() - 1); + else if (Math.abs(x.doubleValue() - 1.0) <= 0.3) { /* * The standard Taylor series around x=1, z=0, z=x-1. * Abramowitz-Stegun 4.124. * The absolute error is err(z)/(1+z) = err(x)/x. */ - final BigDecimal z = scalePrec(x.subtract(BigDecimal.ONE), 2); + final BigDecimal z = BigDecimalMath.scalePrec(x.subtract(BigDecimal.ONE), 2); BigDecimal zpown = z; final double eps = 0.5 * x.ulp().doubleValue() / Math.abs(x.doubleValue()); BigDecimal resul = z; for (int k = 2;; k++) { - zpown = multiplyRound(zpown, z); - final BigDecimal c = divideRound(zpown, k); - if (k % 2 == 0) { + zpown = BigDecimalMath.multiplyRound(zpown, z); + final BigDecimal c = BigDecimalMath.divideRound(zpown, k); + if (k % 2 == 0) resul = resul.subtract(c); - } else { + else resul = resul.add(c); - } - if (Math.abs(c.doubleValue()) < eps) { + if (Math.abs(c.doubleValue()) < eps) break; - } } - final MathContext mc = SafeMathContext.newMathContext(err2prec(resul.doubleValue(), eps)); + final MathContext mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(resul.doubleValue(), eps)); return resul.round(mc); } else { final double xDbl = x.doubleValue(); @@ -563,9 +549,9 @@ public class BigDecimalMath { /* * Compute r-th root with 2 additional digits of precision */ - final BigDecimal xhighpr = scalePrec(x, 2); - BigDecimal resul = root(r, xhighpr); - resul = log(resul).multiply(new BigDecimal(r)); + final BigDecimal xhighpr = BigDecimalMath.scalePrec(x, 2); + BigDecimal resul = BigDecimalMath.root(r, xhighpr); + resul = BigDecimalMath.log(resul).multiply(new BigDecimal(r)); /* * error propagation: log(x+errx) = log(x)+errx/x, so the absolute @@ -573,14 +559,14 @@ public class BigDecimalMath { * in the result equals the relative error in the input, * xUlpDbl/xDbl . */ - final MathContext mc = SafeMathContext.newMathContext(err2prec(resul.doubleValue(), xUlpDbl / xDbl)); + final MathContext mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(resul.doubleValue(), xUlpDbl / xDbl)); return resul.round(mc); } } /* BigDecimalMath.log */ /** * The natural logarithm. - * + * * @param n * The main argument, a strictly positive integer. * @param mc @@ -590,18 +576,18 @@ public class BigDecimalMath { * @author Richard J. Mathar * @throws Error */ - static public BigDecimal log(int n, final MathContext mc) throws Error { + static public BigDecimal log(final int n, final MathContext mc) throws Error { /* * the value is undefined if x is negative. */ - if (n <= 0) { + if (n <= 0) throw new ArithmeticException("Cannot take log of negative " + n); - } else if (n == 1) { + else if (n == 1) return BigDecimal.ZERO; - } else if (n == 2) { - if (mc.getPrecision() < LOG2.precision()) { - return LOG2.round(mc); - } else { + else if (n == 2) { + if (mc.getPrecision() < BigDecimalMath.LOG2.precision()) + return BigDecimalMath.LOG2.round(mc); + else { /* * Broadhurst arXiv:math/9803067= precision/1.87. */ final int kmax = (int) (mc.getPrecision() / 1.87); - MathContext mcloc = SafeMathContext.newMathContext(mc.getPrecision() + 1 + (int) (Math.log10(kmax * 0.693 / 1.098))); - BigDecimal log3 = multiplyRound(log(2, mcloc), 19); + MathContext mcloc = SafeMathContext.newMathContext(mc.getPrecision() + 1 + (int) Math.log10(kmax * 0.693 / 1.098)); + BigDecimal log3 = BigDecimalMath.multiplyRound(BigDecimalMath.log(2, mcloc), 19); /* * log3 is roughly 1, so absolute and relative error are the same. @@ -634,28 +620,26 @@ public class BigDecimalMath { * result will be divided by 12, so a conservative error is the one * already found in mc */ - final double eps = prec2err(1.098, mc.getPrecision()) / kmax; + final double eps = BigDecimalMath.prec2err(1.098, mc.getPrecision()) / kmax; final Rational r = new Rational(7153, 524288); Rational pk = new Rational(7153, 524288); for (int k = 1;; k++) { final Rational tmp = pk.divide(k); - if (tmp.doubleValue() < eps) { + if (tmp.doubleValue() < eps) break; - } /* * how many digits of tmp do we need in the sum? */ - mcloc = SafeMathContext.newMathContext(err2prec(tmp.doubleValue(), eps)); + mcloc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(tmp.doubleValue(), eps)); final BigDecimal c = pk.divide(k).BigDecimalValue(mcloc); - if (k % 2 != 0) { + if (k % 2 != 0) log3 = log3.add(c); - } else { + else log3 = log3.subtract(c); - } pk = pk.multiply(r); } - log3 = divideRound(log3, 12); + log3 = BigDecimalMath.divideRound(log3, 12); return log3.round(mc); } else if (n == 5) { /* @@ -667,8 +651,8 @@ public class BigDecimalMath { * so k>= precision/1.33. */ final int kmax = (int) (mc.getPrecision() / 1.33); - MathContext mcloc = SafeMathContext.newMathContext(mc.getPrecision() + 1 + (int) (Math.log10(kmax * 0.693 / 1.609))); - BigDecimal log5 = multiplyRound(log(2, mcloc), 14); + MathContext mcloc = SafeMathContext.newMathContext(mc.getPrecision() + 1 + (int) Math.log10(kmax * 0.693 / 1.609)); + BigDecimal log5 = BigDecimalMath.multiplyRound(BigDecimalMath.log(2, mcloc), 14); /* * log5 is roughly 1.6, so absolute and relative error are the same. @@ -676,24 +660,23 @@ public class BigDecimalMath { * result will be divided by 6, so a conservative error is the one * already found in mc */ - final double eps = prec2err(1.6, mc.getPrecision()) / kmax; + final double eps = BigDecimalMath.prec2err(1.6, mc.getPrecision()) / kmax; final Rational r = new Rational(759, 16384); Rational pk = new Rational(759, 16384); for (int k = 1;; k++) { final Rational tmp = pk.divide(k); - if (tmp.doubleValue() < eps) { + if (tmp.doubleValue() < eps) break; - } /* * how many digits of tmp do we need in the sum? */ - mcloc = SafeMathContext.newMathContext(err2prec(tmp.doubleValue(), eps)); + mcloc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(tmp.doubleValue(), eps)); final BigDecimal c = pk.divide(k).BigDecimalValue(mcloc); log5 = log5.subtract(c); pk = pk.multiply(r); } - log5 = divideRound(log5, 6); + log5 = BigDecimalMath.divideRound(log5, 6); return log5.round(mc); } else if (n == 7) { /* @@ -705,25 +688,24 @@ public class BigDecimalMath { * so k>= precision/0.903. */ final int kmax = (int) (mc.getPrecision() / 0.903); - MathContext mcloc = SafeMathContext.newMathContext(mc.getPrecision() + 1 + (int) (Math.log10(kmax * 3 * 0.693 / 1.098))); - BigDecimal log7 = multiplyRound(log(2, mcloc), 3); + MathContext mcloc = SafeMathContext.newMathContext(mc.getPrecision() + 1 + (int) Math.log10(kmax * 3 * 0.693 / 1.098)); + BigDecimal log7 = BigDecimalMath.multiplyRound(BigDecimalMath.log(2, mcloc), 3); /* * log7 is roughly 1.9, so absolute and relative error are the same. */ - final double eps = prec2err(1.9, mc.getPrecision()) / kmax; + final double eps = BigDecimalMath.prec2err(1.9, mc.getPrecision()) / kmax; final Rational r = new Rational(1, 8); Rational pk = new Rational(1, 8); for (int k = 1;; k++) { final Rational tmp = pk.divide(k); - if (tmp.doubleValue() < eps) { + if (tmp.doubleValue() < eps) break; - } /* * how many digits of tmp do we need in the sum? */ - mcloc = SafeMathContext.newMathContext(err2prec(tmp.doubleValue(), eps)); + mcloc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(tmp.doubleValue(), eps)); final BigDecimal c = pk.divide(k).BigDecimalValue(mcloc); log7 = log7.subtract(c); pk = pk.multiply(r); @@ -743,7 +725,7 @@ public class BigDecimalMath { * log(n+errn) = log(n)+errn/n = log(n)+eps */ final double res = Math.log(n); - double eps = prec2err(res, mc.getPrecision()); + double eps = BigDecimalMath.prec2err(res, mc.getPrecision()); /* * errn = eps*n, convert absolute error in result to requirement on * absolute error in input @@ -753,19 +735,19 @@ public class BigDecimalMath { * Convert this absolute requirement of error in n to a relative * error in n */ - final MathContext mcloc = SafeMathContext.newMathContext(1 + err2prec(n, eps)); + final MathContext mcloc = SafeMathContext.newMathContext(1 + BigDecimalMath.err2prec(n, eps)); /* * Padd n with a number of zeros to trigger the required accuracy in * the standard signature method */ - final BigDecimal nb = scalePrec(new BigDecimal(n), mcloc); - return log(nb); + final BigDecimal nb = BigDecimalMath.scalePrec(new BigDecimal(n), mcloc); + return BigDecimalMath.log(nb); } } /* log */ /** * The natural logarithm. - * + * * @param r * The main argument, a strictly positive value. * @param mc @@ -778,27 +760,27 @@ public class BigDecimalMath { /* * the value is undefined if x is negative. */ - if (r.compareTo(Rational.ZERO) <= 0) { + if (r.compareTo(Rational.ZERO) <= 0) throw new ArithmeticException("Cannot take log of negative " + r.toString()); - } else if (r.compareTo(Rational.ONE) == 0) { + else if (r.compareTo(Rational.ONE) == 0) return BigDecimal.ZERO; - } else { + else { /* * log(r+epsr) = log(r)+epsr/r. Convert the precision to an absolute * error in the result. * eps contains the required absolute error of the result, epsr/r. */ - final double eps = prec2err(Math.log(r.doubleValue()), mc.getPrecision()); + final double eps = BigDecimalMath.prec2err(Math.log(r.doubleValue()), mc.getPrecision()); /* * Convert this further into a requirement of the relative precision * in r, given that * epsr/r is also the relative precision of r. Add one safety digit. */ - final MathContext mcloc = SafeMathContext.newMathContext(1 + err2prec(eps)); + final MathContext mcloc = SafeMathContext.newMathContext(1 + BigDecimalMath.err2prec(eps)); - final BigDecimal resul = log(r.BigDecimalValue(mcloc)); + final BigDecimal resul = BigDecimalMath.log(r.BigDecimalValue(mcloc)); return resul.round(mc); } @@ -806,7 +788,7 @@ public class BigDecimalMath { /** * Power function. - * + * * @param x * Base of the power. * @param y @@ -817,31 +799,31 @@ public class BigDecimalMath { * @since 2009-06-01 */ static public BigDecimal pow(final BigDecimal x, final BigDecimal y) { - if (x.compareTo(BigDecimal.ZERO) < 0) { + if (x.compareTo(BigDecimal.ZERO) < 0) throw new ArithmeticException("Cannot power negative " + x.toString()); - } else if (x.compareTo(BigDecimal.ZERO) == 0) { + else if (x.compareTo(BigDecimal.ZERO) == 0) return BigDecimal.ZERO; - } else { + else { /* * return x^y = exp(y*log(x)) ; */ - final BigDecimal logx = log(x); + final BigDecimal logx = BigDecimalMath.log(x); final BigDecimal ylogx = y.multiply(logx); - final BigDecimal resul = exp(ylogx); + final BigDecimal resul = BigDecimalMath.exp(ylogx); /* * The estimation of the relative error in the result is * |log(x)*err(y)|+|y*err(x)/x| */ final double errR = Math.abs(logx.doubleValue() * y.ulp().doubleValue() / 2.) + Math.abs(y.doubleValue() * x.ulp().doubleValue() / 2. / x.doubleValue()); - final MathContext mcR = SafeMathContext.newMathContext(err2prec(1.0, errR)); + final MathContext mcR = SafeMathContext.newMathContext(BigDecimalMath.err2prec(1.0, errR)); return resul.round(mcR); } } /* BigDecimalMath.pow */ /** * Raise to an integer power and round. - * + * * @param x * The base. * @param n @@ -854,11 +836,11 @@ public class BigDecimalMath { /** * Special cases: x^1=x and x^0 = 1 */ - if (n == 1) { + if (n == 1) return x; - } else if (n == 0) { + else if (n == 0) return BigDecimal.ONE; - } else { + else { /* * The relative error in the result is n times the relative error in * the input. @@ -867,18 +849,17 @@ public class BigDecimalMath { * Since the standard BigDecimal.pow can only handle positive n, we * split the algorithm. */ - final MathContext mc = SafeMathContext.newMathContext(x.precision() - (int) Math.log10((Math.abs(n)))); - if (n > 0) { + final MathContext mc = SafeMathContext.newMathContext(x.precision() - (int) Math.log10(Math.abs(n))); + if (n > 0) return x.pow(n, mc); - } else { + else return BigDecimal.ONE.divide(x.pow(-n), mc); - } } } /* BigDecimalMath.powRound */ /** * Raise to an integer power and round. - * + * * @param x * The base. * @param n @@ -895,16 +876,15 @@ public class BigDecimalMath { * implemented to decompose larger powers into cascaded calls to smaller * ones. */ - if (n.compareTo(Rational.MAX_INT) > 0 || n.compareTo(Rational.MIN_INT) < 0) { + if (n.compareTo(Rational.MAX_INT) > 0 || n.compareTo(Rational.MIN_INT) < 0) throw new ProviderException("Not implemented: big power " + n.toString()); - } else { - return powRound(x, n.intValue()); - } + else + return BigDecimalMath.powRound(x, n.intValue()); } /* BigDecimalMath.powRound */ /** * Raise to a fractional power and round. - * + * * @param x * The base. * Generally enforced to be positive, with the exception of @@ -920,120 +900,112 @@ public class BigDecimalMath { /** * Special cases: x^1=x and x^0 = 1 */ - if (q.compareTo(BigInteger.ONE) == 0) { + if (q.compareTo(BigInteger.ONE) == 0) return x; - } else if (q.signum() == 0) { + else if (q.signum() == 0) return BigDecimal.ONE; - } else if (q.isInteger()) { + else if (q.isInteger()) /* * We are sure that the denominator is positive here, because * normalize() has been * called during constrution etc. */ - return powRound(x, q.a); - } - /* - * Refuse to operate on the general negative basis. The integer q have - * already been handled above. - */ - else if (x.compareTo(BigDecimal.ZERO) < 0) { + return BigDecimalMath.powRound(x, q.a); + else if (x.compareTo(BigDecimal.ZERO) < 0) throw new ArithmeticException("Cannot power negative " + x.toString()); - } else { - if (q.isIntegerFrac()) { - /* - * Newton method with first estimate in double precision. - * The disadvantage of this first line here is that the result - * must fit in the - * standard range of double precision numbers exponents. - */ - final double estim = Math.pow(x.doubleValue(), q.doubleValue()); - BigDecimal res = new BigDecimal(estim); + else if (q.isIntegerFrac()) { + /* + * Newton method with first estimate in double precision. + * The disadvantage of this first line here is that the result + * must fit in the + * standard range of double precision numbers exponents. + */ + final double estim = Math.pow(x.doubleValue(), q.doubleValue()); + BigDecimal res = new BigDecimal(estim); - /* - * The error in x^q is q*x^(q-1)*Delta(x). - * The relative error is q*Delta(x)/x, q times the relative - * error of x. - */ - final BigDecimal reserr = new BigDecimal(0.5 * q.abs().doubleValue() * x.ulp().divide(x.abs(), MathContext.DECIMAL64).doubleValue()); + /* + * The error in x^q is q*x^(q-1)*Delta(x). + * The relative error is q*Delta(x)/x, q times the relative + * error of x. + */ + final BigDecimal reserr = new BigDecimal(0.5 * q.abs().doubleValue() * x.ulp().divide(x.abs(), MathContext.DECIMAL64).doubleValue()); - /* - * The main point in branching the cases above is that this - * conversion - * will succeed for numerator and denominator of q. - */ - final int qa = q.a.intValue(); - final int qb = q.b.intValue(); + /* + * The main point in branching the cases above is that this + * conversion + * will succeed for numerator and denominator of q. + */ + final int qa = q.a.intValue(); + final int qb = q.b.intValue(); - /* Newton iterations. */ - final BigDecimal xpowa = powRound(x, qa); - for (;;) { + /* Newton iterations. */ + final BigDecimal xpowa = BigDecimalMath.powRound(x, qa); + for (;;) { + /* + * numerator and denominator of the Newton term. The major + * disadvantage of this implementation is that the updates + * of the powers + * of the new estimate are done in full precision calling + * BigDecimal.pow(), + * which becomes slow if the denominator of q is large. + */ + final BigDecimal nu = res.pow(qb).subtract(xpowa); + final BigDecimal de = BigDecimalMath.multiplyRound(res.pow(qb - 1), q.b); + + /* estimated correction */ + BigDecimal eps = nu.divide(de, MathContext.DECIMAL64); + + final BigDecimal err = res.multiply(reserr, MathContext.DECIMAL64); + final int precDiv = 2 + BigDecimalMath.err2prec(eps, err); + if (precDiv <= 0) /* - * numerator and denominator of the Newton term. The major - * disadvantage of this implementation is that the updates - * of the powers - * of the new estimate are done in full precision calling - * BigDecimal.pow(), - * which becomes slow if the denominator of q is large. + * The case when the precision is already reached and + * any precision + * will do. */ - final BigDecimal nu = res.pow(qb).subtract(xpowa); - final BigDecimal de = multiplyRound(res.pow(qb - 1), q.b); - - /* estimated correction */ - BigDecimal eps = nu.divide(de, MathContext.DECIMAL64); - - final BigDecimal err = res.multiply(reserr, MathContext.DECIMAL64); - final int precDiv = 2 + err2prec(eps, err); - if (precDiv <= 0) { - /* - * The case when the precision is already reached and - * any precision - * will do. - */ - eps = nu.divide(de, MathContext.DECIMAL32); - } else { - final MathContext mc = SafeMathContext.newMathContext(precDiv); - eps = nu.divide(de, mc); - } - - res = subtractRound(res, eps); - /* - * reached final precision if the relative error fell below - * reserr, - * |eps/res| < reserr - */ - if (eps.divide(res, MathContext.DECIMAL64).abs().compareTo(reserr) < 0) { - /* - * delete the bits of extra precision kept in this - * working copy. - */ - final MathContext mc = SafeMathContext.newMathContext(err2prec(reserr.doubleValue())); - return res.round(mc); - } + eps = nu.divide(de, MathContext.DECIMAL32); + else { + final MathContext mc = SafeMathContext.newMathContext(precDiv); + eps = nu.divide(de, mc); } - } else { - /* - * The error in x^q is q*x^(q-1)*Delta(x) + Delta(q)*x^q*log(x). - * The relative error is q/x*Delta(x) + Delta(q)*log(x). Convert - * q to a floating point - * number such that its relative error becomes negligible: - * Delta(q)/q << Delta(x)/x/log(x) . - */ - final int precq = 3 + err2prec((x.ulp().divide(x, MathContext.DECIMAL64)).doubleValue() / Math.log(x.doubleValue())); - final MathContext mc = SafeMathContext.newMathContext(precq); + res = BigDecimalMath.subtractRound(res, eps); /* - * Perform the actual calculation as exponentiation of two - * floating point numbers. + * reached final precision if the relative error fell below + * reserr, + * |eps/res| < reserr */ - return pow(x, q.BigDecimalValue(mc)); + if (eps.divide(res, MathContext.DECIMAL64).abs().compareTo(reserr) < 0) { + /* + * delete the bits of extra precision kept in this + * working copy. + */ + final MathContext mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(reserr.doubleValue())); + return res.round(mc); + } } + } else { + /* + * The error in x^q is q*x^(q-1)*Delta(x) + Delta(q)*x^q*log(x). + * The relative error is q/x*Delta(x) + Delta(q)*log(x). Convert + * q to a floating point + * number such that its relative error becomes negligible: + * Delta(q)/q << Delta(x)/x/log(x) . + */ + final int precq = 3 + BigDecimalMath.err2prec(x.ulp().divide(x, MathContext.DECIMAL64).doubleValue() / Math.log(x.doubleValue())); + final MathContext mc = SafeMathContext.newMathContext(precq); + /* + * Perform the actual calculation as exponentiation of two + * floating point numbers. + */ + return BigDecimalMath.pow(x, q.BigDecimalValue(mc)); } } /* BigDecimalMath.powRound */ /** * Trigonometric sine. - * + * * @param x * The argument in radians. * @return sin(x) in the range -1 to 1. @@ -1041,94 +1013,91 @@ public class BigDecimalMath { * @since 2009-06-01 */ static public BigDecimal sin(final BigDecimal x) throws Error { - if (x.compareTo(BigDecimal.ZERO) < 0) { - return sin(x.negate()).negate(); - } else if (x.compareTo(BigDecimal.ZERO) == 0) { + if (x.compareTo(BigDecimal.ZERO) < 0) + return BigDecimalMath.sin(x.negate()).negate(); + else if (x.compareTo(BigDecimal.ZERO) == 0) return BigDecimal.ZERO; - } else { + else { /* * reduce modulo 2pi */ - final BigDecimal res = mod2pi(x); + final BigDecimal res = BigDecimalMath.mod2pi(x); final double errpi = 0.5 * Math.abs(x.ulp().doubleValue()); - MathContext mc = SafeMathContext.newMathContext(2 + err2prec(3.14159, errpi)); - final BigDecimal p = pi(mc); + MathContext mc = SafeMathContext.newMathContext(2 + BigDecimalMath.err2prec(3.14159, errpi)); + final BigDecimal p = BigDecimalMath.pi(mc); mc = SafeMathContext.newMathContext(x.precision()); - if (res.compareTo(p) > 0) { + if (res.compareTo(p) > 0) /* * pi 0) { + return BigDecimalMath.sin(BigDecimalMath.subtractRound(res, p)).negate(); + else if (res.multiply(new BigDecimal("2")).compareTo(p) > 0) /* * pi/2 0) /* - * for the range 0<=xpi/4: sin(x) = cos(pi/2-x) */ - if (res.multiply(new BigDecimal("4")).compareTo(p) > 0) { - /* - * x>pi/4: sin(x) = cos(pi/2-x) - */ - return cos(subtractRound(p.divide(new BigDecimal("2")), res)); - } else { - /* - * Simple Taylor expansion, sum_{i=1..infinity} - * (-1)^(..)res^(2i+1)/(2i+1)! - */ - BigDecimal resul = res; + return BigDecimalMath.cos(BigDecimalMath.subtractRound(p.divide(new BigDecimal("2")), res)); + else { + /* + * Simple Taylor expansion, sum_{i=1..infinity} + * (-1)^(..)res^(2i+1)/(2i+1)! + */ + BigDecimal resul = res; - /* x^i */ - BigDecimal xpowi = res; + /* x^i */ + BigDecimal xpowi = res; - /* 2i+1 factorial */ - BigInteger ifac = BigInteger.ONE; + /* 2i+1 factorial */ + BigInteger ifac = BigInteger.ONE; - /* - * The error in the result is set by the error in x itself. - */ - final double xUlpDbl = res.ulp().doubleValue(); + /* + * The error in the result is set by the error in x itself. + */ + final double xUlpDbl = res.ulp().doubleValue(); + /* + * The error in the result is set by the error in x itself. + * We need at most k terms to squeeze x^(2k+1)/(2k+1)! below + * this value. + * x^(2k+1) < x.ulp; (2k+1)*log10(x) < -x.precision; + * 2k*log10(x)< -x.precision; + * 2k*(-log10(x)) > x.precision; 2k*log10(1/x) > x.precision + */ + final int k = (int) (res.precision() / Math.log10(1.0 / res.doubleValue())) / 2; + final MathContext mcTay = SafeMathContext.newMathContext(BigDecimalMath.err2prec(res.doubleValue(), xUlpDbl / k)); + for (int i = 1;; i++) { /* - * The error in the result is set by the error in x itself. - * We need at most k terms to squeeze x^(2k+1)/(2k+1)! below - * this value. - * x^(2k+1) < x.ulp; (2k+1)*log10(x) < -x.precision; - * 2k*log10(x)< -x.precision; - * 2k*(-log10(x)) > x.precision; 2k*log10(1/x) > x.precision + * TBD: at which precision will 2*i or 2*i+1 overflow? */ - final int k = (int) (res.precision() / Math.log10(1.0 / res.doubleValue())) / 2; - final MathContext mcTay = SafeMathContext.newMathContext(err2prec(res.doubleValue(), xUlpDbl / k)); - for (int i = 1;; i++) { - /* - * TBD: at which precision will 2*i or 2*i+1 overflow? - */ - ifac = ifac.multiply(new BigInteger("" + (2 * i))); - ifac = ifac.multiply(new BigInteger("" + (2 * i + 1))); - xpowi = xpowi.multiply(res).multiply(res).negate(); - final BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay); - resul = resul.add(corr); - if (corr.abs().doubleValue() < 0.5 * xUlpDbl) { - break; - } - } - /* - * The error in the result is set by the error in x itself. - */ - mc = SafeMathContext.newMathContext(res.precision()); - return resul.round(mc); + ifac = ifac.multiply(new BigInteger("" + 2 * i)); + ifac = ifac.multiply(new BigInteger("" + (2 * i + 1))); + xpowi = xpowi.multiply(res).multiply(res).negate(); + final BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay); + resul = resul.add(corr); + if (corr.abs().doubleValue() < 0.5 * xUlpDbl) + break; } + /* + * The error in the result is set by the error in x itself. + */ + mc = SafeMathContext.newMathContext(res.precision()); + return resul.round(mc); } } } /* sin */ /** * Trigonometric cosine. - * + * * @param x * The argument in radians. * @return cos(x) in the range -1 to 1. @@ -1136,111 +1105,108 @@ public class BigDecimalMath { * @since 2009-06-01 */ static public BigDecimal cos(final BigDecimal x) throws Error { - if (x.compareTo(BigDecimal.ZERO) < 0) { - return cos(x.negate()); - } else if (x.compareTo(BigDecimal.ZERO) == 0) { + if (x.compareTo(BigDecimal.ZERO) < 0) + return BigDecimalMath.cos(x.negate()); + else if (x.compareTo(BigDecimal.ZERO) == 0) return BigDecimal.ONE; - } else { + else { /* * reduce modulo 2pi */ - final BigDecimal res = mod2pi(x); + final BigDecimal res = BigDecimalMath.mod2pi(x); final double errpi = 0.5 * Math.abs(x.ulp().doubleValue()); - MathContext mc = SafeMathContext.newMathContext(2 + err2prec(3.14159, errpi)); - final BigDecimal p = pi(mc); + MathContext mc = SafeMathContext.newMathContext(2 + BigDecimalMath.err2prec(3.14159, errpi)); + final BigDecimal p = BigDecimalMath.pi(mc); mc = SafeMathContext.newMathContext(x.precision()); - if (res.compareTo(p) > 0) { + if (res.compareTo(p) > 0) /* * pi 0) { + return BigDecimalMath.cos(BigDecimalMath.subtractRound(res, p)).negate(); + else if (res.multiply(new BigDecimal("2")).compareTo(p) > 0) /* * pi/2 0) /* - * for the range 0<=xpi/4: cos(x) = sin(pi/2-x) */ - if (res.multiply(new BigDecimal("4")).compareTo(p) > 0) { - /* - * x>pi/4: cos(x) = sin(pi/2-x) - */ - return sin(subtractRound(p.divide(new BigDecimal("2")), res)); - } else { - /* - * Simple Taylor expansion, sum_{i=0..infinity} - * (-1)^(..)res^(2i)/(2i)! - */ - BigDecimal resul = BigDecimal.ONE; + return BigDecimalMath.sin(BigDecimalMath.subtractRound(p.divide(new BigDecimal("2")), res)); + else { + /* + * Simple Taylor expansion, sum_{i=0..infinity} + * (-1)^(..)res^(2i)/(2i)! + */ + BigDecimal resul = BigDecimal.ONE; - /* x^i */ - BigDecimal xpowi = BigDecimal.ONE; + /* x^i */ + BigDecimal xpowi = BigDecimal.ONE; - /* 2i factorial */ - BigInteger ifac = BigInteger.ONE; + /* 2i factorial */ + BigInteger ifac = BigInteger.ONE; - /* - * The absolute error in the result is the error in x^2/2 - * which is x times the error in x. - */ - final double xUlpDbl = 0.5 * res.ulp().doubleValue() * res.doubleValue(); + /* + * The absolute error in the result is the error in x^2/2 + * which is x times the error in x. + */ + final double xUlpDbl = 0.5 * res.ulp().doubleValue() * res.doubleValue(); + /* + * The error in the result is set by the error in x^2/2 + * itself, xUlpDbl. + * We need at most k terms to push x^(2k+1)/(2k+1)! below + * this value. + * x^(2k) < xUlpDbl; (2k)*log(x) < log(xUlpDbl); + */ + final int k = (int) (Math.log(xUlpDbl) / Math.log(res.doubleValue())) / 2; + final MathContext mcTay = SafeMathContext.newMathContext(BigDecimalMath.err2prec(1., xUlpDbl / k)); + for (int i = 1;; i++) { /* - * The error in the result is set by the error in x^2/2 - * itself, xUlpDbl. - * We need at most k terms to push x^(2k+1)/(2k+1)! below - * this value. - * x^(2k) < xUlpDbl; (2k)*log(x) < log(xUlpDbl); + * TBD: at which precision will 2*i-1 or 2*i overflow? */ - final int k = (int) (Math.log(xUlpDbl) / Math.log(res.doubleValue())) / 2; - final MathContext mcTay = SafeMathContext.newMathContext(err2prec(1., xUlpDbl / k)); - for (int i = 1;; i++) { - /* - * TBD: at which precision will 2*i-1 or 2*i overflow? - */ - ifac = ifac.multiply(new BigInteger("" + (2 * i - 1))); - ifac = ifac.multiply(new BigInteger("" + (2 * i))); - xpowi = xpowi.multiply(res).multiply(res).negate(); - final BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay); - resul = resul.add(corr); - if (corr.abs().doubleValue() < 0.5 * xUlpDbl) { - break; - } - } - /* - * The error in the result is governed by the error in x - * itself. - */ - mc = SafeMathContext.newMathContext(err2prec(resul.doubleValue(), xUlpDbl)); - return resul.round(mc); + ifac = ifac.multiply(new BigInteger("" + (2 * i - 1))); + ifac = ifac.multiply(new BigInteger("" + 2 * i)); + xpowi = xpowi.multiply(res).multiply(res).negate(); + final BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay); + resul = resul.add(corr); + if (corr.abs().doubleValue() < 0.5 * xUlpDbl) + break; } + /* + * The error in the result is governed by the error in x + * itself. + */ + mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(resul.doubleValue(), xUlpDbl)); + return resul.round(mc); } } } /* BigDecimalMath.cos */ /** * The trigonometric tangent. - * + * * @param x * the argument in radians. * @return the tan(x) * @throws Error */ static public BigDecimal tan(final BigDecimal x) throws Error { - if (x.compareTo(BigDecimal.ZERO) == 0) { + if (x.compareTo(BigDecimal.ZERO) == 0) return BigDecimal.ZERO; - } else if (x.compareTo(BigDecimal.ZERO) < 0) { - return tan(x.negate()).negate(); - } else { + else if (x.compareTo(BigDecimal.ZERO) < 0) + return BigDecimalMath.tan(x.negate()).negate(); + else { /* * reduce modulo pi */ - final BigDecimal res = modpi(x); + final BigDecimal res = BigDecimalMath.modpi(x); /* * absolute error in the result is err(x)/cos^2(x) to lowest order @@ -1251,12 +1217,12 @@ public class BigDecimalMath { if (xDbl > 0.8) { /* tan(x) = 1/cot(x) */ - final BigDecimal co = cot(x); - final MathContext mc = SafeMathContext.newMathContext(err2prec(1. / co.doubleValue(), eps)); + final BigDecimal co = BigDecimalMath.cot(x); + final MathContext mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(1. / co.doubleValue(), eps)); return BigDecimal.ONE.divide(co, mc); } else { - final BigDecimal xhighpr = scalePrec(res, 2); - final BigDecimal xhighprSq = multiplyRound(xhighpr, xhighpr); + final BigDecimal xhighpr = BigDecimalMath.scalePrec(res, 2); + final BigDecimal xhighprSq = BigDecimalMath.multiplyRound(xhighpr, xhighpr); BigDecimal resul = xhighpr.plus(); @@ -1273,16 +1239,15 @@ public class BigDecimalMath { for (int i = 2;; i++) { Rational f = b.at(2 * i).abs(); fourn = fourn.shiftLeft(2); - fac = fac.multiply(new BigInteger("" + (2 * i))).multiply(new BigInteger("" + (2 * i - 1))); + fac = fac.multiply(new BigInteger("" + 2 * i)).multiply(new BigInteger("" + (2 * i - 1))); f = f.multiply(fourn).multiply(fourn.subtract(BigInteger.ONE)).divide(fac); - xpowi = multiplyRound(xpowi, xhighprSq); - final BigDecimal c = multiplyRound(xpowi, f); + xpowi = BigDecimalMath.multiplyRound(xpowi, xhighprSq); + final BigDecimal c = BigDecimalMath.multiplyRound(xpowi, f); resul = resul.add(c); - if (Math.abs(c.doubleValue()) < 0.1 * eps) { + if (Math.abs(c.doubleValue()) < 0.1 * eps) break; - } } - final MathContext mc = SafeMathContext.newMathContext(err2prec(resul.doubleValue(), eps)); + final MathContext mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(resul.doubleValue(), eps)); return resul.round(mc); } } @@ -1290,7 +1255,7 @@ public class BigDecimalMath { /** * The trigonometric co-tangent. - * + * * @param x * the argument in radians. * @return the cot(x) @@ -1298,15 +1263,15 @@ public class BigDecimalMath { * @since 2009-07-31 */ static public BigDecimal cot(final BigDecimal x) throws Error { - if (x.compareTo(BigDecimal.ZERO) == 0) { + if (x.compareTo(BigDecimal.ZERO) == 0) throw new ArithmeticException("Cannot take cot of zero " + x.toString()); - } else if (x.compareTo(BigDecimal.ZERO) < 0) { - return cot(x.negate()).negate(); - } else { + else if (x.compareTo(BigDecimal.ZERO) < 0) + return BigDecimalMath.cot(x.negate()).negate(); + else { /* * reduce modulo pi */ - final BigDecimal res = modpi(x); + final BigDecimal res = BigDecimalMath.modpi(x); /* * absolute error in the result is err(x)/sin^2(x) to lowest order @@ -1315,10 +1280,10 @@ public class BigDecimalMath { final double xUlpDbl = x.ulp().doubleValue() / 2.; final double eps = xUlpDbl / 2. / Math.pow(Math.sin(xDbl), 2.); - final BigDecimal xhighpr = scalePrec(res, 2); - final BigDecimal xhighprSq = multiplyRound(xhighpr, xhighpr); + final BigDecimal xhighpr = BigDecimalMath.scalePrec(res, 2); + final BigDecimal xhighprSq = BigDecimalMath.multiplyRound(xhighpr, xhighpr); - MathContext mc = SafeMathContext.newMathContext(err2prec(xhighpr.doubleValue(), eps)); + MathContext mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(xhighpr.doubleValue(), eps)); BigDecimal resul = BigDecimal.ONE.divide(xhighpr, mc); /* x^(2i-1) */ @@ -1333,56 +1298,54 @@ public class BigDecimalMath { for (int i = 1;; i++) { Rational f = b.at(2 * i); - fac = fac.multiply(new BigInteger("" + (2 * i))).multiply(new BigInteger("" + (2 * i - 1))); + fac = fac.multiply(new BigInteger("" + 2 * i)).multiply(new BigInteger("" + (2 * i - 1))); f = f.multiply(fourn).divide(fac); - final BigDecimal c = multiplyRound(xpowi, f); - if (i % 2 == 0) { + final BigDecimal c = BigDecimalMath.multiplyRound(xpowi, f); + if (i % 2 == 0) resul = resul.add(c); - } else { + else resul = resul.subtract(c); - } - if (Math.abs(c.doubleValue()) < 0.1 * eps) { + if (Math.abs(c.doubleValue()) < 0.1 * eps) break; - } fourn = fourn.shiftLeft(2); - xpowi = multiplyRound(xpowi, xhighprSq); + xpowi = BigDecimalMath.multiplyRound(xpowi, xhighprSq); } - mc = SafeMathContext.newMathContext(err2prec(resul.doubleValue(), eps)); + mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(resul.doubleValue(), eps)); return resul.round(mc); } } /* BigDecimalMath.cot */ /** * The inverse trigonometric sine. - * + * * @param x * the argument. * @return the arcsin(x) in radians. * @throws Error */ static public BigDecimal asin(final BigDecimal x) throws Error { - if (x.compareTo(BigDecimal.ONE) > 0 || x.compareTo(BigDecimal.ONE.negate()) < 0) { + if (x.compareTo(BigDecimal.ONE) > 0 || x.compareTo(BigDecimal.ONE.negate()) < 0) throw new ArithmeticException("Out of range argument " + x.toString() + " of asin"); - } else if (x.compareTo(BigDecimal.ZERO) == 0) { + else if (x.compareTo(BigDecimal.ZERO) == 0) return BigDecimal.ZERO; - } else if (x.compareTo(BigDecimal.ONE) == 0) { + else if (x.compareTo(BigDecimal.ONE) == 0) { /* * arcsin(1) = pi/2 */ final double errpi = Math.sqrt(x.ulp().doubleValue()); - final MathContext mc = SafeMathContext.newMathContext(err2prec(3.14159, errpi)); - return pi(mc).divide(new BigDecimal(2)); - } else if (x.compareTo(BigDecimal.ZERO) < 0) { - return asin(x.negate()).negate(); - } else if (x.doubleValue() > 0.7) { + final MathContext mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(3.14159, errpi)); + return BigDecimalMath.pi(mc).divide(new BigDecimal(2)); + } else if (x.compareTo(BigDecimal.ZERO) < 0) + return BigDecimalMath.asin(x.negate()).negate(); + else if (x.doubleValue() > 0.7) { final BigDecimal xCompl = BigDecimal.ONE.subtract(x); final double xDbl = x.doubleValue(); final double xUlpDbl = x.ulp().doubleValue() / 2.; final double eps = xUlpDbl / 2. / Math.sqrt(1. - Math.pow(xDbl, 2.)); - final BigDecimal xhighpr = scalePrec(xCompl, 3); - final BigDecimal xhighprV = divideRound(xhighpr, 4); + final BigDecimal xhighpr = BigDecimalMath.scalePrec(xCompl, 3); + final BigDecimal xhighprV = BigDecimalMath.divideRound(xhighpr, 4); BigDecimal resul = BigDecimal.ONE; @@ -1396,31 +1359,29 @@ public class BigDecimalMath { for (int i = 1;; i++) { ifacN = ifacN.multiply(new BigInteger("" + (2 * i - 1))); ifacD = ifacD.multiply(new BigInteger("" + i)); - if (i == 1) { + if (i == 1) xpowi = xhighprV; - } else { - xpowi = multiplyRound(xpowi, xhighprV); - } - final BigDecimal c = divideRound(multiplyRound(xpowi, ifacN), ifacD.multiply(new BigInteger("" + (2 * i + 1)))); + else + xpowi = BigDecimalMath.multiplyRound(xpowi, xhighprV); + final BigDecimal c = BigDecimalMath.divideRound(BigDecimalMath.multiplyRound(xpowi, ifacN), ifacD.multiply(new BigInteger("" + (2 * i + 1)))); resul = resul.add(c); /* * series started 1+x/12+... which yields an estimate of the * sum's error */ - if (Math.abs(c.doubleValue()) < xUlpDbl / 120.) { + if (Math.abs(c.doubleValue()) < xUlpDbl / 120.) break; - } } /* * sqrt(2*z)*(1+...) */ - xpowi = sqrt(xhighpr.multiply(new BigDecimal(2))); - resul = multiplyRound(xpowi, resul); + xpowi = BigDecimalMath.sqrt(xhighpr.multiply(new BigDecimal(2))); + resul = BigDecimalMath.multiplyRound(xpowi, resul); MathContext mc = SafeMathContext.newMathContext(resul.precision()); - final BigDecimal pihalf = pi(mc).divide(new BigDecimal(2)); + final BigDecimal pihalf = BigDecimalMath.pi(mc).divide(new BigDecimal(2)); - mc = SafeMathContext.newMathContext(err2prec(resul.doubleValue(), eps)); + mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(resul.doubleValue(), eps)); return pihalf.subtract(resul, mc); } else { /* @@ -1431,8 +1392,8 @@ public class BigDecimalMath { final double xUlpDbl = x.ulp().doubleValue() / 2.; final double eps = xUlpDbl / 2. / Math.sqrt(1. - Math.pow(xDbl, 2.)); - final BigDecimal xhighpr = scalePrec(x, 2); - final BigDecimal xhighprSq = multiplyRound(xhighpr, xhighpr); + final BigDecimal xhighpr = BigDecimalMath.scalePrec(x, 2); + final BigDecimal xhighprSq = BigDecimalMath.multiplyRound(xhighpr, xhighpr); BigDecimal resul = xhighpr.plus(); @@ -1445,22 +1406,21 @@ public class BigDecimalMath { for (int i = 1;; i++) { ifacN = ifacN.multiply(new BigInteger("" + (2 * i - 1))); - ifacD = ifacD.multiply(new BigInteger("" + (2 * i))); - xpowi = multiplyRound(xpowi, xhighprSq); - final BigDecimal c = divideRound(multiplyRound(xpowi, ifacN), ifacD.multiply(new BigInteger("" + (2 * i + 1)))); + ifacD = ifacD.multiply(new BigInteger("" + 2 * i)); + xpowi = BigDecimalMath.multiplyRound(xpowi, xhighprSq); + final BigDecimal c = BigDecimalMath.divideRound(BigDecimalMath.multiplyRound(xpowi, ifacN), ifacD.multiply(new BigInteger("" + (2 * i + 1)))); resul = resul.add(c); - if (Math.abs(c.doubleValue()) < 0.1 * eps) { + if (Math.abs(c.doubleValue()) < 0.1 * eps) break; - } } - final MathContext mc = SafeMathContext.newMathContext(err2prec(resul.doubleValue(), eps)); + final MathContext mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(resul.doubleValue(), eps)); return resul.round(mc); } } /* BigDecimalMath.asin */ /** * The inverse trigonometric cosine. - * + * * @param x * the argument. * @return the arccos(x) in radians. @@ -1471,12 +1431,12 @@ public class BigDecimalMath { /* * Essentially forwarded to pi/2 - asin(x) */ - final BigDecimal xhighpr = scalePrec(x, 2); - BigDecimal resul = asin(xhighpr); + final BigDecimal xhighpr = BigDecimalMath.scalePrec(x, 2); + BigDecimal resul = BigDecimalMath.asin(xhighpr); double eps = resul.ulp().doubleValue() / 2.; - MathContext mc = SafeMathContext.newMathContext(err2prec(3.14159, eps)); - final BigDecimal pihalf = pi(mc).divide(new BigDecimal(2)); + MathContext mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(3.14159, eps)); + final BigDecimal pihalf = BigDecimalMath.pi(mc).divide(new BigDecimal(2)); resul = pihalf.subtract(resul); /* @@ -1486,14 +1446,14 @@ public class BigDecimalMath { final double xUlpDbl = x.ulp().doubleValue() / 2.; eps = xUlpDbl / 2. / Math.sqrt(1. - Math.pow(xDbl, 2.)); - mc = SafeMathContext.newMathContext(err2prec(resul.doubleValue(), eps)); + mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(resul.doubleValue(), eps)); return resul.round(mc); } /* BigDecimalMath.acos */ /** * The inverse trigonometric tangent. - * + * * @param x * the argument. * @return the principal value of arctan(x) in radians in the range -pi/2 to @@ -1502,35 +1462,35 @@ public class BigDecimalMath { * @since 2009-08-03 */ static public BigDecimal atan(final BigDecimal x) throws Error { - if (x.compareTo(BigDecimal.ZERO) < 0) { - return atan(x.negate()).negate(); - } else if (x.compareTo(BigDecimal.ZERO) == 0) { + if (x.compareTo(BigDecimal.ZERO) < 0) + return BigDecimalMath.atan(x.negate()).negate(); + else if (x.compareTo(BigDecimal.ZERO) == 0) return BigDecimal.ZERO; - } else if (x.doubleValue() > 0.7 && x.doubleValue() < 3.0) { + else if (x.doubleValue() > 0.7 && x.doubleValue() < 3.0) { /* * Abramowitz-Stegun 4.4.34 convergence acceleration * 2*arctan(x) = arctan(2x/(1-x^2)) = arctan(y). x=(sqrt(1+y^2)-1)/y * This maps 0<=y<=3 to 0<=x<=0.73 roughly. Temporarily with 2 * protectionist digits. */ - final BigDecimal y = scalePrec(x, 2); - final BigDecimal newx = divideRound(hypot(1, y).subtract(BigDecimal.ONE), y); + final BigDecimal y = BigDecimalMath.scalePrec(x, 2); + final BigDecimal newx = BigDecimalMath.divideRound(BigDecimalMath.hypot(1, y).subtract(BigDecimal.ONE), y); /* intermediate result with too optimistic error estimate */ - final BigDecimal resul = multiplyRound(atan(newx), 2); + final BigDecimal resul = BigDecimalMath.multiplyRound(BigDecimalMath.atan(newx), 2); /* * absolute error in the result is errx/(1+x^2), where errx = half * of the ulp. */ final double eps = x.ulp().doubleValue() / (2.0 * Math.hypot(1.0, x.doubleValue())); - final MathContext mc = SafeMathContext.newMathContext(err2prec(resul.doubleValue(), eps)); + final MathContext mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(resul.doubleValue(), eps)); return resul.round(mc); } else if (x.doubleValue() < 0.71) { /* Taylor expansion around x=0; Abramowitz-Stegun 4.4.42 */ - final BigDecimal xhighpr = scalePrec(x, 2); - final BigDecimal xhighprSq = multiplyRound(xhighpr, xhighpr).negate(); + final BigDecimal xhighpr = BigDecimalMath.scalePrec(x, 2); + final BigDecimal xhighprSq = BigDecimalMath.multiplyRound(xhighpr, xhighpr).negate(); BigDecimal resul = xhighpr.plus(); @@ -1544,15 +1504,14 @@ public class BigDecimalMath { final double eps = x.ulp().doubleValue() / (2.0 * Math.hypot(1.0, x.doubleValue())); for (int i = 1;; i++) { - xpowi = multiplyRound(xpowi, xhighprSq); - final BigDecimal c = divideRound(xpowi, 2 * i + 1); + xpowi = BigDecimalMath.multiplyRound(xpowi, xhighprSq); + final BigDecimal c = BigDecimalMath.divideRound(xpowi, 2 * i + 1); resul = resul.add(c); - if (Math.abs(c.doubleValue()) < 0.1 * eps) { + if (Math.abs(c.doubleValue()) < 0.1 * eps) break; - } } - final MathContext mc = SafeMathContext.newMathContext(err2prec(resul.doubleValue(), eps)); + final MathContext mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(resul.doubleValue(), eps)); return resul.round(mc); } else { /* Taylor expansion around x=infinity; Abramowitz-Stegun 4.4.42 */ @@ -1567,33 +1526,32 @@ public class BigDecimalMath { * start with the term pi/2; gather its precision relative to the * expected result */ - MathContext mc = SafeMathContext.newMathContext(2 + err2prec(3.1416, eps)); - final BigDecimal onepi = pi(mc); + MathContext mc = SafeMathContext.newMathContext(2 + BigDecimalMath.err2prec(3.1416, eps)); + final BigDecimal onepi = BigDecimalMath.pi(mc); BigDecimal resul = onepi.divide(new BigDecimal(2)); - final BigDecimal xhighpr = divideRound(-1, scalePrec(x, 2)); - final BigDecimal xhighprSq = multiplyRound(xhighpr, xhighpr).negate(); + final BigDecimal xhighpr = BigDecimalMath.divideRound(-1, BigDecimalMath.scalePrec(x, 2)); + final BigDecimal xhighprSq = BigDecimalMath.multiplyRound(xhighpr, xhighpr).negate(); /* signed x^(2i+1) */ BigDecimal xpowi = xhighpr; for (int i = 0;; i++) { - final BigDecimal c = divideRound(xpowi, 2 * i + 1); + final BigDecimal c = BigDecimalMath.divideRound(xpowi, 2 * i + 1); resul = resul.add(c); - if (Math.abs(c.doubleValue()) < 0.1 * eps) { + if (Math.abs(c.doubleValue()) < 0.1 * eps) break; - } - xpowi = multiplyRound(xpowi, xhighprSq); + xpowi = BigDecimalMath.multiplyRound(xpowi, xhighprSq); } - mc = SafeMathContext.newMathContext(err2prec(resul.doubleValue(), eps)); + mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(resul.doubleValue(), eps)); return resul.round(mc); } } /* BigDecimalMath.atan */ /** * The hyperbolic cosine. - * + * * @param x * The argument. * @return The cosh(x) = (exp(x)+exp(-x))/2 . @@ -1602,74 +1560,71 @@ public class BigDecimalMath { * @since 2009-08-19 */ static public BigDecimal cosh(final BigDecimal x) throws Error { - if (x.compareTo(BigDecimal.ZERO) < 0) { - return cos(x.negate()); - } else if (x.compareTo(BigDecimal.ZERO) == 0) { + if (x.compareTo(BigDecimal.ZERO) < 0) + return BigDecimalMath.cos(x.negate()); + else if (x.compareTo(BigDecimal.ZERO) == 0) return BigDecimal.ONE; - } else { - if (x.doubleValue() > 1.5) { - /* - * cosh^2(x) = 1+ sinh^2(x). - */ - return hypot(1, sinh(x)); - } else { - final BigDecimal xhighpr = scalePrec(x, 2); - /* Simple Taylor expansion, sum_{0=1..infinity} x^(2i)/(2i)! */ - BigDecimal resul = BigDecimal.ONE; + else if (x.doubleValue() > 1.5) + /* + * cosh^2(x) = 1+ sinh^2(x). + */ + return BigDecimalMath.hypot(1, BigDecimalMath.sinh(x)); + else { + final BigDecimal xhighpr = BigDecimalMath.scalePrec(x, 2); + /* Simple Taylor expansion, sum_{0=1..infinity} x^(2i)/(2i)! */ + BigDecimal resul = BigDecimal.ONE; - /* x^i */ - BigDecimal xpowi = BigDecimal.ONE; + /* x^i */ + BigDecimal xpowi = BigDecimal.ONE; - /* 2i factorial */ - BigInteger ifac = BigInteger.ONE; + /* 2i factorial */ + BigInteger ifac = BigInteger.ONE; - /* - * The absolute error in the result is the error in x^2/2 which - * is x times the error in x. - */ - final double xUlpDbl = 0.5 * x.ulp().doubleValue() * x.doubleValue(); + /* + * The absolute error in the result is the error in x^2/2 which + * is x times the error in x. + */ + final double xUlpDbl = 0.5 * x.ulp().doubleValue() * x.doubleValue(); - /* - * The error in the result is set by the error in x^2/2 itself, - * xUlpDbl. - * We need at most k terms to push x^(2k)/(2k)! below this - * value. - * x^(2k) < xUlpDbl; (2k)*log(x) < log(xUlpDbl); - */ - final int k = (int) (Math.log(xUlpDbl) / Math.log(x.doubleValue())) / 2; + /* + * The error in the result is set by the error in x^2/2 itself, + * xUlpDbl. + * We need at most k terms to push x^(2k)/(2k)! below this + * value. + * x^(2k) < xUlpDbl; (2k)*log(x) < log(xUlpDbl); + */ + final int k = (int) (Math.log(xUlpDbl) / Math.log(x.doubleValue())) / 2; + /* + * The individual terms are all smaller than 1, so an estimate + * of 1.0 for + * the absolute value will give a safe relative error estimate + * for the indivdual terms + */ + final MathContext mcTay = SafeMathContext.newMathContext(BigDecimalMath.err2prec(1., xUlpDbl / k)); + for (int i = 1;; i++) { /* - * The individual terms are all smaller than 1, so an estimate - * of 1.0 for - * the absolute value will give a safe relative error estimate - * for the indivdual terms + * TBD: at which precision will 2*i-1 or 2*i overflow? */ - final MathContext mcTay = SafeMathContext.newMathContext(err2prec(1., xUlpDbl / k)); - for (int i = 1;; i++) { - /* - * TBD: at which precision will 2*i-1 or 2*i overflow? - */ - ifac = ifac.multiply(new BigInteger("" + (2 * i - 1))); - ifac = ifac.multiply(new BigInteger("" + (2 * i))); - xpowi = xpowi.multiply(xhighpr).multiply(xhighpr); - final BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay); - resul = resul.add(corr); - if (corr.abs().doubleValue() < 0.5 * xUlpDbl) { - break; - } - } - /* - * The error in the result is governed by the error in x itself. - */ - final MathContext mc = SafeMathContext.newMathContext(err2prec(resul.doubleValue(), xUlpDbl)); - return resul.round(mc); + ifac = ifac.multiply(new BigInteger("" + (2 * i - 1))); + ifac = ifac.multiply(new BigInteger("" + 2 * i)); + xpowi = xpowi.multiply(xhighpr).multiply(xhighpr); + final BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay); + resul = resul.add(corr); + if (corr.abs().doubleValue() < 0.5 * xUlpDbl) + break; } + /* + * The error in the result is governed by the error in x itself. + */ + final MathContext mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(resul.doubleValue(), xUlpDbl)); + return resul.round(mc); } } /* BigDecimalMath.cosh */ /** * The hyperbolic sine. - * + * * @param x * the argument. * @return the sinh(x) = (exp(x)-exp(-x))/2 . @@ -1678,81 +1633,78 @@ public class BigDecimalMath { * @since 2009-08-19 */ static public BigDecimal sinh(final BigDecimal x) throws Error { - if (x.compareTo(BigDecimal.ZERO) < 0) { - return sinh(x.negate()).negate(); - } else if (x.compareTo(BigDecimal.ZERO) == 0) { + if (x.compareTo(BigDecimal.ZERO) < 0) + return BigDecimalMath.sinh(x.negate()).negate(); + else if (x.compareTo(BigDecimal.ZERO) == 0) return BigDecimal.ZERO; + else if (x.doubleValue() > 2.4) { + /* + * Move closer to zero with sinh(2x)= 2*sinh(x)*cosh(x). + */ + final BigDecimal two = new BigDecimal(2); + final BigDecimal xhalf = x.divide(two); + final BigDecimal resul = BigDecimalMath.sinh(xhalf).multiply(BigDecimalMath.cosh(xhalf)).multiply(two); + /* + * The error in the result is set by the error in x itself. + * The first derivative of sinh(x) is cosh(x), so the absolute + * error + * in the result is cosh(x)*errx, and the relative error is + * coth(x)*errx = errx/tanh(x) + */ + final double eps = Math.tanh(x.doubleValue()); + final MathContext mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(0.5 * x.ulp().doubleValue() / eps)); + return resul.round(mc); } else { - if (x.doubleValue() > 2.4) { - /* - * Move closer to zero with sinh(2x)= 2*sinh(x)*cosh(x). - */ - final BigDecimal two = new BigDecimal(2); - final BigDecimal xhalf = x.divide(two); - final BigDecimal resul = sinh(xhalf).multiply(cosh(xhalf)).multiply(two); - /* - * The error in the result is set by the error in x itself. - * The first derivative of sinh(x) is cosh(x), so the absolute - * error - * in the result is cosh(x)*errx, and the relative error is - * coth(x)*errx = errx/tanh(x) - */ - final double eps = Math.tanh(x.doubleValue()); - final MathContext mc = SafeMathContext.newMathContext(err2prec(0.5 * x.ulp().doubleValue() / eps)); - return resul.round(mc); - } else { - final BigDecimal xhighpr = scalePrec(x, 2); - /* - * Simple Taylor expansion, sum_{i=0..infinity} x^(2i+1)/(2i+1)! - */ - BigDecimal resul = xhighpr; + final BigDecimal xhighpr = BigDecimalMath.scalePrec(x, 2); + /* + * Simple Taylor expansion, sum_{i=0..infinity} x^(2i+1)/(2i+1)! + */ + BigDecimal resul = xhighpr; - /* x^i */ - BigDecimal xpowi = xhighpr; + /* x^i */ + BigDecimal xpowi = xhighpr; - /* 2i+1 factorial */ - BigInteger ifac = BigInteger.ONE; + /* 2i+1 factorial */ + BigInteger ifac = BigInteger.ONE; - /* - * The error in the result is set by the error in x itself. - */ - final double xUlpDbl = x.ulp().doubleValue(); + /* + * The error in the result is set by the error in x itself. + */ + final double xUlpDbl = x.ulp().doubleValue(); + /* + * The error in the result is set by the error in x itself. + * We need at most k terms to squeeze x^(2k+1)/(2k+1)! below + * this value. + * x^(2k+1) < x.ulp; (2k+1)*log10(x) < -x.precision; + * 2k*log10(x)< -x.precision; + * 2k*(-log10(x)) > x.precision; 2k*log10(1/x) > x.precision + */ + final int k = (int) (x.precision() / Math.log10(1.0 / xhighpr.doubleValue())) / 2; + final MathContext mcTay = SafeMathContext.newMathContext(BigDecimalMath.err2prec(x.doubleValue(), xUlpDbl / k)); + for (int i = 1;; i++) { /* - * The error in the result is set by the error in x itself. - * We need at most k terms to squeeze x^(2k+1)/(2k+1)! below - * this value. - * x^(2k+1) < x.ulp; (2k+1)*log10(x) < -x.precision; - * 2k*log10(x)< -x.precision; - * 2k*(-log10(x)) > x.precision; 2k*log10(1/x) > x.precision + * TBD: at which precision will 2*i or 2*i+1 overflow? */ - final int k = (int) (x.precision() / Math.log10(1.0 / xhighpr.doubleValue())) / 2; - final MathContext mcTay = SafeMathContext.newMathContext(err2prec(x.doubleValue(), xUlpDbl / k)); - for (int i = 1;; i++) { - /* - * TBD: at which precision will 2*i or 2*i+1 overflow? - */ - ifac = ifac.multiply(new BigInteger("" + (2 * i))); - ifac = ifac.multiply(new BigInteger("" + (2 * i + 1))); - xpowi = xpowi.multiply(xhighpr).multiply(xhighpr); - final BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay); - resul = resul.add(corr); - if (corr.abs().doubleValue() < 0.5 * xUlpDbl) { - break; - } - } - /* - * The error in the result is set by the error in x itself. - */ - final MathContext mc = SafeMathContext.newMathContext(x.precision()); - return resul.round(mc); + ifac = ifac.multiply(new BigInteger("" + 2 * i)); + ifac = ifac.multiply(new BigInteger("" + (2 * i + 1))); + xpowi = xpowi.multiply(xhighpr).multiply(xhighpr); + final BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay); + resul = resul.add(corr); + if (corr.abs().doubleValue() < 0.5 * xUlpDbl) + break; } + /* + * The error in the result is set by the error in x itself. + */ + final MathContext mc = SafeMathContext.newMathContext(x.precision()); + return resul.round(mc); } } /* BigDecimalMath.sinh */ /** * The hyperbolic tangent. - * + * * @param x * The argument. * @return The tanh(x) = sinh(x)/cosh(x). @@ -1760,30 +1712,30 @@ public class BigDecimalMath { * @since 2009-08-20 */ static public BigDecimal tanh(final BigDecimal x) { - if (x.compareTo(BigDecimal.ZERO) < 0) { - return tanh(x.negate()).negate(); - } else if (x.compareTo(BigDecimal.ZERO) == 0) { + if (x.compareTo(BigDecimal.ZERO) < 0) + return BigDecimalMath.tanh(x.negate()).negate(); + else if (x.compareTo(BigDecimal.ZERO) == 0) return BigDecimal.ZERO; - } else { - final BigDecimal xhighpr = scalePrec(x, 2); + else { + final BigDecimal xhighpr = BigDecimalMath.scalePrec(x, 2); /* * tanh(x) = (1-e^(-2x))/(1+e^(-2x)) . */ - final BigDecimal exp2x = exp(xhighpr.multiply(new BigDecimal(-2))); + final BigDecimal exp2x = BigDecimalMath.exp(xhighpr.multiply(new BigDecimal(-2))); /* * The error in tanh x is err(x)/cosh^2(x). */ final double eps = 0.5 * x.ulp().doubleValue() / Math.pow(Math.cosh(x.doubleValue()), 2.0); - final MathContext mc = SafeMathContext.newMathContext(err2prec(Math.tanh(x.doubleValue()), eps)); + final MathContext mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(Math.tanh(x.doubleValue()), eps)); return BigDecimal.ONE.subtract(exp2x).divide(BigDecimal.ONE.add(exp2x), mc); } } /* BigDecimalMath.tanh */ /** * The inverse hyperbolic sine. - * + * * @param x * The argument. * @return The arcsinh(x) . @@ -1791,29 +1743,29 @@ public class BigDecimalMath { * @since 2009-08-20 */ static public BigDecimal asinh(final BigDecimal x) { - if (x.compareTo(BigDecimal.ZERO) == 0) { + if (x.compareTo(BigDecimal.ZERO) == 0) return BigDecimal.ZERO; - } else { - final BigDecimal xhighpr = scalePrec(x, 2); + else { + final BigDecimal xhighpr = BigDecimalMath.scalePrec(x, 2); /* * arcsinh(x) = log(x+hypot(1,x)) */ - final BigDecimal logx = log(hypot(1, xhighpr).add(xhighpr)); + final BigDecimal logx = BigDecimalMath.log(BigDecimalMath.hypot(1, xhighpr).add(xhighpr)); /* * The absolute error in arcsinh x is err(x)/sqrt(1+x^2) */ final double xDbl = x.doubleValue(); final double eps = 0.5 * x.ulp().doubleValue() / Math.hypot(1., xDbl); - final MathContext mc = SafeMathContext.newMathContext(err2prec(logx.doubleValue(), eps)); + final MathContext mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(logx.doubleValue(), eps)); return logx.round(mc); } } /* BigDecimalMath.asinh */ /** * The inverse hyperbolic cosine. - * + * * @param x * The argument. * @return The arccosh(x) . @@ -1821,31 +1773,31 @@ public class BigDecimalMath { * @since 2009-08-20 */ static public BigDecimal acosh(final BigDecimal x) { - if (x.compareTo(BigDecimal.ONE) < 0) { + if (x.compareTo(BigDecimal.ONE) < 0) throw new ArithmeticException("Out of range argument cosh " + x.toString()); - } else if (x.compareTo(BigDecimal.ONE) == 0) { + else if (x.compareTo(BigDecimal.ONE) == 0) return BigDecimal.ZERO; - } else { - final BigDecimal xhighpr = scalePrec(x, 2); + else { + final BigDecimal xhighpr = BigDecimalMath.scalePrec(x, 2); /* * arccosh(x) = log(x+sqrt(x^2-1)) */ - final BigDecimal logx = log(sqrt(xhighpr.pow(2).subtract(BigDecimal.ONE)).add(xhighpr)); + final BigDecimal logx = BigDecimalMath.log(BigDecimalMath.sqrt(xhighpr.pow(2).subtract(BigDecimal.ONE)).add(xhighpr)); /* * The absolute error in arcsinh x is err(x)/sqrt(x^2-1) */ final double xDbl = x.doubleValue(); final double eps = 0.5 * x.ulp().doubleValue() / Math.sqrt(xDbl * xDbl - 1.); - final MathContext mc = SafeMathContext.newMathContext(err2prec(logx.doubleValue(), eps)); + final MathContext mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(logx.doubleValue(), eps)); return logx.round(mc); } } /* BigDecimalMath.acosh */ /** * The Gamma function. - * + * * @param x * The argument. * @return Gamma(x). @@ -1857,15 +1809,15 @@ public class BigDecimalMath { * reduce to interval near 1.0 with the functional relation, * Abramowitz-Stegun 6.1.33 */ - if (x.compareTo(BigDecimal.ZERO) < 0) { - return divideRound(Gamma(x.add(BigDecimal.ONE)), x); - } else if (x.doubleValue() > 1.5) { + if (x.compareTo(BigDecimal.ZERO) < 0) + return BigDecimalMath.divideRound(BigDecimalMath.Gamma(x.add(BigDecimal.ONE)), x); + else if (x.doubleValue() > 1.5) { /* * Gamma(x) = Gamma(xmin+n) = Gamma(xmin)*Pochhammer(xmin,n). */ final int n = (int) (x.doubleValue() - 0.5); final BigDecimal xmin1 = x.subtract(new BigDecimal(n)); - return multiplyRound(Gamma(xmin1), pochhammer(xmin1, n)); + return BigDecimalMath.multiplyRound(BigDecimalMath.Gamma(xmin1), BigDecimalMath.pochhammer(xmin1, n)); } else { /* * apply Abramowitz-Stegun 6.1.33 @@ -1875,7 +1827,7 @@ public class BigDecimalMath { /* * add intermediately 2 digits to the partial sum accumulation */ - z = scalePrec(z, 2); + z = BigDecimalMath.scalePrec(z, 2); MathContext mcloc = SafeMathContext.newMathContext(z.precision()); /* @@ -1884,12 +1836,12 @@ public class BigDecimalMath { */ double eps = x.ulp().doubleValue() / x.doubleValue(); - BigDecimal resul = log(scalePrec(x, 2)).negate(); + BigDecimal resul = BigDecimalMath.log(BigDecimalMath.scalePrec(x, 2)).negate(); if (x.compareTo(BigDecimal.ONE) != 0) { - final BigDecimal gammCompl = BigDecimal.ONE.subtract(gamma(mcloc)); - resul = resul.add(multiplyRound(z, gammCompl)); + final BigDecimal gammCompl = BigDecimal.ONE.subtract(BigDecimalMath.gamma(mcloc)); + resul = resul.add(BigDecimalMath.multiplyRound(z, gammCompl)); for (int n = 2;; n++) { /* * multiplying z^n/n by zeta(n-1) means that the two @@ -1900,8 +1852,8 @@ public class BigDecimalMath { * error of thelatter is the * absolute error in z) */ - BigDecimal c = divideRound(z.pow(n, mcloc), n); - MathContext m = SafeMathContext.newMathContext(err2prec(n * z.ulp().doubleValue() / 2. / z.doubleValue())); + BigDecimal c = BigDecimalMath.divideRound(z.pow(n, mcloc), n); + MathContext m = SafeMathContext.newMathContext(BigDecimalMath.err2prec(n * z.ulp().doubleValue() / 2. / z.doubleValue())); c = c.round(m); /* @@ -1916,27 +1868,24 @@ public class BigDecimalMath { * error in zeta, because zeta is * of the order of 1. */ - if (eps / 100. / c.doubleValue() < 0.01) { - m = SafeMathContext.newMathContext(err2prec(eps / 100. / c.doubleValue())); - } else { + if (eps / 100. / c.doubleValue() < 0.01) + m = SafeMathContext.newMathContext(BigDecimalMath.err2prec(eps / 100. / c.doubleValue())); + else m = SafeMathContext.newMathContext(2); - } /* zeta(n) -1 */ - final BigDecimal zetm1 = zeta(n, m).subtract(BigDecimal.ONE); - c = multiplyRound(c, zetm1); + final BigDecimal zetm1 = BigDecimalMath.zeta(n, m).subtract(BigDecimal.ONE); + c = BigDecimalMath.multiplyRound(c, zetm1); - if (n % 2 == 0) { + if (n % 2 == 0) resul = resul.add(c); - } else { + else resul = resul.subtract(c); - } /* * alternating sum, so truncating as eps is reached suffices */ - if (Math.abs(c.doubleValue()) < eps) { + if (Math.abs(c.doubleValue()) < eps) break; - } } } @@ -1945,15 +1894,15 @@ public class BigDecimalMath { * input variable times the digamma (psi) value at that point. */ final double zdbl = z.doubleValue(); - eps = psi(zdbl) * x.ulp().doubleValue() / 2.; - mcloc = SafeMathContext.newMathContext(err2prec(eps)); - return exp(resul).round(mcloc); + eps = BigDecimalMath.psi(zdbl) * x.ulp().doubleValue() / 2.; + mcloc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(eps)); + return BigDecimalMath.exp(resul).round(mcloc); } } /* BigDecimalMath.gamma */ /** * The Gamma function. - * + * * @param q * The argument. * @param mc @@ -1964,19 +1913,19 @@ public class BigDecimalMath { */ static public BigDecimal Gamma(final Rational q, final MathContext mc) throws Error { if (q.isBigInteger()) { - if (q.compareTo(Rational.ZERO) <= 0) { + if (q.compareTo(Rational.ZERO) <= 0) throw new ArithmeticException("Gamma at " + q.toString()); - } else { + else { /* Gamma(n) = (n-1)! */ final Factorial f = new Factorial(); final BigInteger g = f.at(q.trunc().intValue() - 1); - return scalePrec(new BigDecimal(g), mc); + return BigDecimalMath.scalePrec(new BigDecimal(g), mc); } } else if (q.b.intValue() == 2) { /* * half integer cases which are related to sqrt(pi) */ - final BigDecimal p = sqrt(pi(mc)); + final BigDecimal p = BigDecimalMath.sqrt(BigDecimalMath.pi(mc)); if (q.compareTo(Rational.ZERO) >= 0) { Rational pro = Rational.ONE; Rational f = q.subtract(1); @@ -1984,7 +1933,7 @@ public class BigDecimalMath { pro = pro.multiply(f); f = f.subtract(1); } - return multiplyRound(p, pro); + return BigDecimalMath.multiplyRound(p, pro); } else { Rational pro = Rational.ONE; Rational f = q; @@ -1992,7 +1941,7 @@ public class BigDecimalMath { pro = pro.divide(f); f = f.add(1); } - return multiplyRound(p, pro); + return BigDecimalMath.multiplyRound(p, pro); } } else { /* @@ -2001,19 +1950,19 @@ public class BigDecimalMath { * that this is equivalent to mc: Delta(x) = precision/psi(x). */ final double qdbl = q.doubleValue(); - final double deltx = 5. * Math.pow(10., -mc.getPrecision()) / psi(qdbl); + final double deltx = 5. * Math.pow(10., -mc.getPrecision()) / BigDecimalMath.psi(qdbl); - final MathContext mcx = SafeMathContext.newMathContext(err2prec(qdbl, deltx)); + final MathContext mcx = SafeMathContext.newMathContext(BigDecimalMath.err2prec(qdbl, deltx)); final BigDecimal x = q.BigDecimalValue(mcx); /* forward calculation to the general floating point case */ - return Gamma(x); + return BigDecimalMath.Gamma(x); } } /* BigDecimalMath.Gamma */ /** * Pochhammer's function. - * + * * @param x * The main argument. * @param n @@ -2026,15 +1975,15 @@ public class BigDecimalMath { * reduce to interval near 1.0 with the functional relation, * Abramowitz-Stegun 6.1.33 */ - if (n < 0) { + if (n < 0) throw new ProviderException("Not implemented: pochhammer with negative index " + n); - } else if (n == 0) { + else if (n == 0) return BigDecimal.ONE; - } else { + else { /* * internally two safety digits */ - final BigDecimal xhighpr = scalePrec(x, 2); + final BigDecimal xhighpr = BigDecimalMath.scalePrec(x, 2); BigDecimal resul = xhighpr; final double xUlpDbl = x.ulp().doubleValue(); @@ -2047,23 +1996,23 @@ public class BigDecimalMath { for (int i = 1; i < n; i++) { eps += 0.5 * xUlpDbl / Math.abs(xDbl + i); resul = resul.multiply(xhighpr.add(new BigDecimal(i))); - final MathContext mcloc = SafeMathContext.newMathContext(4 + err2prec(eps)); + final MathContext mcloc = SafeMathContext.newMathContext(4 + BigDecimalMath.err2prec(eps)); resul = resul.round(mcloc); } - return resul.round(SafeMathContext.newMathContext(err2prec(eps))); + return resul.round(SafeMathContext.newMathContext(BigDecimalMath.err2prec(eps))); } } /* BigDecimalMath.pochhammer */ /** * Reduce value to the interval [0,2*Pi]. - * + * * @param x * the original value * @return the value modulo 2*pi in the interval from 0 to 2*pi. * @throws Error * @since 2009-06-01 */ - static public BigDecimal mod2pi(BigDecimal x) throws Error { + static public BigDecimal mod2pi(final BigDecimal x) throws Error { /* * write x= 2*pi*k+r with the precision in r defined by the precision of * x and not @@ -2079,13 +2028,12 @@ public class BigDecimalMath { * with two safety digits */ double err2pi; - if (k != 0) { + if (k != 0) err2pi = 0.25 * Math.abs(x.ulp().doubleValue() / k); - } else { + else err2pi = 0.5 * Math.abs(x.ulp().doubleValue()); - } - MathContext mc = SafeMathContext.newMathContext(2 + err2prec(6.283, err2pi)); - final BigDecimal twopi = pi(mc).multiply(new BigDecimal(2)); + MathContext mc = SafeMathContext.newMathContext(2 + BigDecimalMath.err2prec(6.283, err2pi)); + final BigDecimal twopi = BigDecimalMath.pi(mc).multiply(new BigDecimal(2)); /* * Delegate the actual operation to the BigDecimal class, which may @@ -2093,28 +2041,27 @@ public class BigDecimalMath { * a negative value of x was negative . */ BigDecimal res = x.remainder(twopi); - if (res.compareTo(BigDecimal.ZERO) < 0) { + if (res.compareTo(BigDecimal.ZERO) < 0) res = res.add(twopi); - } /* * The actual precision is set by the input value, its absolute value of * x.ulp()/2. */ - mc = SafeMathContext.newMathContext(err2prec(res.doubleValue(), x.ulp().doubleValue() / 2.)); + mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(res.doubleValue(), x.ulp().doubleValue() / 2.)); return res.round(mc); } /* mod2pi */ /** * Reduce value to the interval [-Pi/2,Pi/2]. - * + * * @param x * The original value * @return The value modulo pi, shifted to the interval from -Pi/2 to Pi/2. * @throws Error * @since 2009-07-31 */ - static public BigDecimal modpi(BigDecimal x) throws Error { + static public BigDecimal modpi(final BigDecimal x) throws Error { /* * write x= pi*k+r with the precision in r defined by the precision of x * and not @@ -2130,13 +2077,12 @@ public class BigDecimalMath { * two safety digits */ double errpi; - if (k != 0) { + if (k != 0) errpi = 0.5 * Math.abs(x.ulp().doubleValue() / k); - } else { + else errpi = 0.5 * Math.abs(x.ulp().doubleValue()); - } - MathContext mc = SafeMathContext.newMathContext(2 + err2prec(3.1416, errpi)); - final BigDecimal onepi = pi(mc); + MathContext mc = SafeMathContext.newMathContext(2 + BigDecimalMath.err2prec(3.1416, errpi)); + final BigDecimal onepi = BigDecimalMath.pi(mc); final BigDecimal pihalf = onepi.divide(new BigDecimal(2)); /* @@ -2145,23 +2091,22 @@ public class BigDecimalMath { * a negative value of x was negative . */ BigDecimal res = x.remainder(onepi); - if (res.compareTo(pihalf) > 0) { + if (res.compareTo(pihalf) > 0) res = res.subtract(onepi); - } else if (res.compareTo(pihalf.negate()) < 0) { + else if (res.compareTo(pihalf.negate()) < 0) res = res.add(onepi); - } /* * The actual precision is set by the input value, its absolute value of * x.ulp()/2. */ - mc = SafeMathContext.newMathContext(err2prec(res.doubleValue(), x.ulp().doubleValue() / 2.)); + mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(res.doubleValue(), x.ulp().doubleValue() / 2.)); return res.round(mc); } /* modpi */ /** * Riemann zeta function. - * + * * @param n * The positive integer argument. * @param mc @@ -2171,20 +2116,18 @@ public class BigDecimalMath { * @since 2009-08-05 */ static public BigDecimal zeta(final int n, final MathContext mc) throws Error { - if (n <= 0) { + if (n <= 0) throw new ProviderException("Not implemented: zeta at negative argument " + n); - } - if (n == 1) { + if (n == 1) throw new ArithmeticException("Pole at zeta(1) "); - } if (n % 2 == 0) { /* * Even indices. Abramowitz-Stegun 23.2.16. Start with * 2^(n-1)*B(n)/n! */ - Rational b = (new Bernoulli()).at(n).abs(); - b = b.divide((new Factorial()).at(n)); + Rational b = new Bernoulli().at(n).abs(); + b = b.divide(new Factorial().at(n)); b = b.multiply(BigInteger.ONE.shiftLeft(n - 1)); /* @@ -2195,9 +2138,9 @@ public class BigDecimalMath { * Need one more digit in pi if n=10, two digits if n=100 etc, and * add one extra digit. */ - final MathContext mcpi = SafeMathContext.newMathContext(mc.getPrecision() + (int) (Math.log10(10.0 * n))); - final BigDecimal piton = pi(mcpi).pow(n, mc); - return multiplyRound(piton, b); + final MathContext mcpi = SafeMathContext.newMathContext(mc.getPrecision() + (int) Math.log10(10.0 * n)); + final BigDecimal piton = BigDecimalMath.pi(mcpi).pow(n, mc); + return BigDecimalMath.multiplyRound(piton, b); } else if (n == 3) { /* * Broadhurst BBP = 0; i--) { + for (int i = psiT0.length - 1; i >= 0; i--) resul = resul * xdiff + psiT0[i]; - } return resul * xdiff; } else if (x < 0.) { /* Reflection formula */ final double xmin = 1. - x; - return psi(xmin) + Math.PI / Math.tan(Math.PI * xmin); + return BigDecimalMath.psi(xmin) + Math.PI / Math.tan(Math.PI * xmin); } else { final double xmin1 = x - 1; double resul = 0.; for (int k = 26; k >= 1; k--) { - resul -= zeta1(2 * k + 1); + resul -= BigDecimalMath.zeta1(2 * k + 1); resul *= xmin1 * xmin1; } /* 0.422... = 1 -gamma */ @@ -2451,7 +2389,7 @@ public class BigDecimalMath { /** * Broadhurst ladder sequence. - * + * * @param a * The vector of 8 integer arguments * @param mc @@ -2461,21 +2399,21 @@ public class BigDecimalMath { * @since 2009-08-09 * @see arXiv:math/9803067 */ - static protected BigDecimal broadhurstBBP(final int n, final int p, final int a[], MathContext mc) throws Error { + static protected BigDecimal broadhurstBBP(final int n, final int p, final int a[], final MathContext mc) + throws Error { /* * Explore the actual magnitude of the result first with a quick * estimate. */ double x = 0.0; - for (int k = 1; k < 10; k++) { + for (int k = 1; k < 10; k++) x += a[(k - 1) % 8] / Math.pow(2., p * (k + 1) / 2) / Math.pow(k, n); - } /* * Convert the relative precision and estimate of the result into an * absolute precision. */ - double eps = prec2err(x, mc.getPrecision()); + double eps = BigDecimalMath.prec2err(x, mc.getPrecision()); /* * Divide this through the number of terms in the sum to account for @@ -2494,7 +2432,7 @@ public class BigDecimalMath { for (int c = 0;; c++) { Rational r = new Rational(); for (int k = 0; k < 8; k++) { - Rational tmp = new Rational(new BigInteger("" + a[k]), (new BigInteger("" + (1 + 8 * c + k))).pow(n)); + Rational tmp = new Rational(new BigInteger("" + a[k]), new BigInteger("" + (1 + 8 * c + k)).pow(n)); /* * floor( (pk+p)/2) */ @@ -2503,10 +2441,9 @@ public class BigDecimalMath { r = r.add(tmp); } - if (Math.abs(r.doubleValue()) < eps) { + if (Math.abs(r.doubleValue()) < eps) break; - } - final MathContext mcloc = SafeMathContext.newMathContext(1 + err2prec(r.doubleValue(), eps)); + final MathContext mcloc = SafeMathContext.newMathContext(1 + BigDecimalMath.err2prec(r.doubleValue(), eps)); res = res.add(r.BigDecimalValue(mcloc)); } return res.round(mc); @@ -2514,7 +2451,7 @@ public class BigDecimalMath { /** * Add a BigDecimal and a BigInteger. - * + * * @param x * The left summand * @param y @@ -2528,7 +2465,7 @@ public class BigDecimalMath { /** * Add and round according to the larger of the two ulp's. - * + * * @param x * The left summand * @param y @@ -2543,17 +2480,16 @@ public class BigDecimalMath { * |err(y)|+|err(x)| */ final double errR = Math.abs(y.ulp().doubleValue() / 2.) + Math.abs(x.ulp().doubleValue() / 2.); - int err2prec = err2prec(resul.doubleValue(), errR); - if (err2prec < 0) { + int err2prec = BigDecimalMath.err2prec(resul.doubleValue(), errR); + if (err2prec < 0) err2prec = 0; - } final MathContext mc = SafeMathContext.newMathContext(err2prec); return resul.round(mc); } /* addRound */ /** * Add and round according to the larger of the two ulp's. - * + * * @param x * The left summand * @param y @@ -2562,13 +2498,13 @@ public class BigDecimalMath { * @since 2010-07-19 */ static public BigComplex addRound(final BigComplex x, final BigDecimal y) { - final BigDecimal R = addRound(x.re, y); + final BigDecimal R = BigDecimalMath.addRound(x.re, y); return new BigComplex(R, x.im); } /* addRound */ /** * Add and round according to the larger of the two ulp's. - * + * * @param x * The left summand * @param y @@ -2577,14 +2513,14 @@ public class BigDecimalMath { * @since 2010-07-19 */ static public BigComplex addRound(final BigComplex x, final BigComplex y) { - final BigDecimal R = addRound(x.re, y.re); - final BigDecimal I = addRound(x.im, y.im); + final BigDecimal R = BigDecimalMath.addRound(x.re, y.re); + final BigDecimal I = BigDecimalMath.addRound(x.im, y.im); return new BigComplex(R, I); } /* addRound */ /** * Subtract and round according to the larger of the two ulp's. - * + * * @param x * The left term. * @param y @@ -2599,13 +2535,13 @@ public class BigDecimalMath { * |err(y)|+|err(x)| */ final double errR = Math.abs(y.ulp().doubleValue() / 2.) + Math.abs(x.ulp().doubleValue() / 2.); - final MathContext mc = SafeMathContext.newMathContext(err2prec(resul.doubleValue(), errR)); + final MathContext mc = SafeMathContext.newMathContext(BigDecimalMath.err2prec(resul.doubleValue(), errR)); return resul.round(mc); } /* subtractRound */ /** * Subtract and round according to the larger of the two ulp's. - * + * * @param x * The left summand * @param y @@ -2614,14 +2550,14 @@ public class BigDecimalMath { * @since 2010-07-19 */ static public BigComplex subtractRound(final BigComplex x, final BigComplex y) { - final BigDecimal R = subtractRound(x.re, y.re); - final BigDecimal I = subtractRound(x.im, y.im); + final BigDecimal R = BigDecimalMath.subtractRound(x.re, y.re); + final BigDecimal I = BigDecimalMath.subtractRound(x.im, y.im); return new BigComplex(R, I); } /* subtractRound */ /** * Multiply and round. - * + * * @param x * The left factor. * @param y @@ -2642,7 +2578,7 @@ public class BigDecimalMath { /** * Multiply and round. - * + * * @param x * The left factor. * @param y @@ -2651,14 +2587,14 @@ public class BigDecimalMath { * @since 2010-07-19 */ static public BigComplex multiplyRound(final BigComplex x, final BigDecimal y) { - final BigDecimal R = multiplyRound(x.re, y); - final BigDecimal I = multiplyRound(x.im, y); + final BigDecimal R = BigDecimalMath.multiplyRound(x.re, y); + final BigDecimal I = BigDecimalMath.multiplyRound(x.im, y); return new BigComplex(R, I); } /* multiplyRound */ /** * Multiply and round. - * + * * @param x * The left factor. * @param y @@ -2667,14 +2603,14 @@ public class BigDecimalMath { * @since 2010-07-19 */ static public BigComplex multiplyRound(final BigComplex x, final BigComplex y) { - final BigDecimal R = subtractRound(multiplyRound(x.re, y.re), multiplyRound(x.im, y.im)); - final BigDecimal I = addRound(multiplyRound(x.re, y.im), multiplyRound(x.im, y.re)); + final BigDecimal R = BigDecimalMath.subtractRound(BigDecimalMath.multiplyRound(x.re, y.re), BigDecimalMath.multiplyRound(x.im, y.im)); + final BigDecimal I = BigDecimalMath.addRound(BigDecimalMath.multiplyRound(x.re, y.im), BigDecimalMath.multiplyRound(x.im, y.re)); return new BigComplex(R, I); } /* multiplyRound */ /** * Multiply and round. - * + * * @param x * The left factor. * @param f @@ -2683,9 +2619,9 @@ public class BigDecimalMath { * @since 2009-07-30 */ static public BigDecimal multiplyRound(final BigDecimal x, final Rational f) { - if (f.compareTo(BigInteger.ZERO) == 0) { + if (f.compareTo(BigInteger.ZERO) == 0) return BigDecimal.ZERO; - } else { + else { /* * Convert the rational value with two digits of extra precision */ @@ -2696,13 +2632,13 @@ public class BigDecimalMath { * and the precision of the product is then dominated by the * precision in x */ - return multiplyRound(x, fbd); + return BigDecimalMath.multiplyRound(x, fbd); } } /** * Multiply and round. - * + * * @param x * The left factor. * @param n @@ -2721,7 +2657,7 @@ public class BigDecimalMath { /** * Multiply and round. - * + * * @param x * The left factor. * @param n @@ -2740,7 +2676,7 @@ public class BigDecimalMath { /** * Divide and round. - * + * * @param x * The numerator * @param y @@ -2761,12 +2697,12 @@ public class BigDecimalMath { * a smaller apparent accuracy than starte... add missing trailing zeros * now. */ - return scalePrec(resul, mc); + return BigDecimalMath.scalePrec(resul, mc); } /** * Build the inverse and maintain the approximate accuracy. - * + * * @param z * The denominator * @return The divided 1/z = [Re(z)-i*Im(z)]/ [Re^2 z + Im^2 z] @@ -2789,8 +2725,8 @@ public class BigDecimalMath { /* * 1/(x.re+I*x.im) = 1/(x.re+x.im^2/x.re) - I /(x.im +x.re^2/x.im) */ - BigDecimal R = addRound(z.re, divideRound(multiplyRound(z.im, z.im), z.re)); - BigDecimal I = addRound(z.im, divideRound(multiplyRound(z.re, z.re), z.im)); + BigDecimal R = BigDecimalMath.addRound(z.re, BigDecimalMath.divideRound(BigDecimalMath.multiplyRound(z.im, z.im), z.re)); + BigDecimal I = BigDecimalMath.addRound(z.im, BigDecimalMath.divideRound(BigDecimalMath.multiplyRound(z.re, z.re), z.im)); MathContext mc = SafeMathContext.newMathContext(1 + R.precision()); R = BigDecimal.ONE.divide(R, mc); mc = SafeMathContext.newMathContext(1 + I.precision()); @@ -2801,7 +2737,7 @@ public class BigDecimalMath { /** * Divide and round. - * + * * @param x * The numerator * @param y @@ -2810,12 +2746,12 @@ public class BigDecimalMath { * @since 2010-07-19 */ static public BigComplex divideRound(final BigComplex x, final BigComplex y) { - return multiplyRound(x, invertRound(y)); + return BigDecimalMath.multiplyRound(x, BigDecimalMath.invertRound(y)); } /** * Divide and round. - * + * * @param x * The numerator * @param n @@ -2833,7 +2769,7 @@ public class BigDecimalMath { /** * Divide and round. - * + * * @param x * The numerator * @param n @@ -2851,7 +2787,7 @@ public class BigDecimalMath { /** * Divide and round. - * + * * @param n * The numerator * @param x @@ -2869,7 +2805,7 @@ public class BigDecimalMath { /** * Divide and round. - * + * * @param n * The numerator * @param x @@ -2881,24 +2817,23 @@ public class BigDecimalMath { /* * catch case of real-valued denominator first */ - if (x.im.compareTo(BigDecimal.ZERO) == 0) { - return new BigComplex(divideRound(n, x.re), BigDecimal.ZERO); - } else if (x.re.compareTo(BigDecimal.ZERO) == 0) { - return new BigComplex(BigDecimal.ZERO, divideRound(n, x.im).negate()); - } + if (x.im.compareTo(BigDecimal.ZERO) == 0) + return new BigComplex(BigDecimalMath.divideRound(n, x.re), BigDecimal.ZERO); + else if (x.re.compareTo(BigDecimal.ZERO) == 0) + return new BigComplex(BigDecimal.ZERO, BigDecimalMath.divideRound(n, x.im).negate()); - final BigComplex z = invertRound(x); + final BigComplex z = BigDecimalMath.invertRound(x); /* * n/(x+iy) = nx/(x^2+y^2) -nyi/(x^2+y^2) */ - final BigDecimal repart = multiplyRound(z.re, n); - final BigDecimal impart = multiplyRound(z.im, n); + final BigDecimal repart = BigDecimalMath.multiplyRound(z.re, n); + final BigDecimal impart = BigDecimalMath.multiplyRound(z.im, n); return new BigComplex(repart, impart); } /* divideRound */ /** * Divide and round. - * + * * @param n * The numerator. * @param x @@ -2918,7 +2853,7 @@ public class BigDecimalMath { * Append decimal zeros to the value. This returns a value which appears to * have * a higher precision than the input. - * + * * @param x * The input value * @param d @@ -2927,7 +2862,7 @@ public class BigDecimalMath { * @return The same value as the input but with increased (pseudo) * precision. */ - static public BigDecimal scalePrec(final BigDecimal x, int d) { + static public BigDecimal scalePrec(final BigDecimal x, final int d) { return x.setScale(d + x.scale()); } @@ -2935,7 +2870,7 @@ public class BigDecimalMath { * Append decimal zeros to the value. This returns a value which appears to * have * a higher precision than the input. - * + * * @param x * The input value * @param d @@ -2944,15 +2879,15 @@ public class BigDecimalMath { * @return The same value as the input but with increased (pseudo) * precision. */ - static public BigComplex scalePrec(final BigComplex x, int d) { - return new BigComplex(scalePrec(x.re, d), scalePrec(x.im, d)); + static public BigComplex scalePrec(final BigComplex x, final int d) { + return new BigComplex(BigDecimalMath.scalePrec(x.re, d), BigDecimalMath.scalePrec(x.im, d)); } /** * Boost the precision by appending decimal zeros to the value. This returns * a value which appears to have * a higher precision than the input. - * + * * @param x * The input value * @param mc @@ -2962,16 +2897,15 @@ public class BigDecimalMath { */ static public BigDecimal scalePrec(final BigDecimal x, final MathContext mc) { final int diffPr = mc.getPrecision() - x.precision(); - if (diffPr > 0) { - return scalePrec(x, diffPr); - } else { + if (diffPr > 0) + return BigDecimalMath.scalePrec(x, diffPr); + else return x; - } } /* BigDecimalMath.scalePrec */ /** * Convert an absolute error to a precision. - * + * * @param x * The value of the variable * @param xerr @@ -2981,13 +2915,13 @@ public class BigDecimalMath { * reason. * @since 2009-06-25 */ - static public int err2prec(BigDecimal x, BigDecimal xerr) { - return err2prec(xerr.divide(x, MathContext.DECIMAL64).doubleValue()); + static public int err2prec(final BigDecimal x, final BigDecimal xerr) { + return BigDecimalMath.err2prec(xerr.divide(x, MathContext.DECIMAL64).doubleValue()); } /** * Convert an absolute error to a precision. - * + * * @param x * The value of the variable * The value returned depends only on the absolute value, not on @@ -3004,17 +2938,17 @@ public class BigDecimalMath { * reason. * @since 2009-05-30 */ - static public int err2prec(double x, double xerr) { + static public int err2prec(final double x, final double xerr) { /* * Example: an error of xerr=+-0.5 at x=100 represents 100+-0.5 with * a precision = 3 (digits). */ - return 1 + (int) (Math.log10(Math.abs(0.5 * x / xerr))); + return 1 + (int) Math.log10(Math.abs(0.5 * x / xerr)); } /** * Convert a relative error to a precision. - * + * * @param xerr * The relative error in the variable. * The value returned depends only on the absolute value, not on @@ -3024,18 +2958,18 @@ public class BigDecimalMath { * reason. * @since 2009-08-05 */ - static public int err2prec(double xerr) { + static public int err2prec(final double xerr) { /* * Example: an error of xerr=+-0.5 a precision of 1 (digit), an error of * +-0.05 a precision of 2 (digits) */ - return 1 + (int) (Math.log10(Math.abs(0.5 / xerr))); + return 1 + (int) Math.log10(Math.abs(0.5 / xerr)); } /** * Convert a precision (relative error) to an absolute error. * The is the inverse functionality of err2prec(). - * + * * @param x * The value of the variable * The value returned depends only on the absolute value, not on diff --git a/core/src/main/java/org/nevec/rjm/BigIntegerMath.java b/core/src/main/java/org/nevec/rjm/BigIntegerMath.java index 1c750453..86894453 100644 --- a/core/src/main/java/org/nevec/rjm/BigIntegerMath.java +++ b/core/src/main/java/org/nevec/rjm/BigIntegerMath.java @@ -7,7 +7,7 @@ import it.cavallium.warppi.util.Error; /** * BigInteger special functions and Number theory. - * + * * @since 2009-08-06 * @author Richard J. Mathar */ @@ -15,7 +15,7 @@ public class BigIntegerMath { /** * Evaluate binomial(n,k). - * + * * @param n * The upper index * @param k @@ -23,23 +23,20 @@ public class BigIntegerMath { * @return The binomial coefficient */ static public BigInteger binomial(final int n, final int k) { - if (k == 0) { - return (BigInteger.ONE); - } + if (k == 0) + return BigInteger.ONE; BigInteger bin = new BigInteger("" + n); final BigInteger n2 = bin; - for (BigInteger i = new BigInteger("" + (k - 1)); i.compareTo(BigInteger.ONE) >= 0; i = i.subtract(BigInteger.ONE)) { + for (BigInteger i = new BigInteger("" + (k - 1)); i.compareTo(BigInteger.ONE) >= 0; i = i.subtract(BigInteger.ONE)) bin = bin.multiply(n2.subtract(i)); - } - for (BigInteger i = new BigInteger("" + k); i.compareTo(BigInteger.ONE) == 1; i = i.subtract(BigInteger.ONE)) { + for (BigInteger i = new BigInteger("" + k); i.compareTo(BigInteger.ONE) == 1; i = i.subtract(BigInteger.ONE)) bin = bin.divide(i); - } - return (bin); + return bin; } /* binomial */ /** * Evaluate binomial(n,k). - * + * * @param n * The upper index * @param k @@ -51,9 +48,8 @@ public class BigIntegerMath { /* * binomial(n,0) =1 */ - if (k.compareTo(BigInteger.ZERO) == 0) { - return (BigInteger.ONE); - } + if (k.compareTo(BigInteger.ZERO) == 0) + return BigInteger.ONE; BigInteger bin = new BigInteger("" + n); @@ -82,9 +78,8 @@ public class BigIntegerMath { * and in the integer domain. First replace C(n,k) by C(n,n-k) if n-k * Deprecated: This function is extremely slow and inefficient! - * + * * @param n * The integer of which the divisors are to be found. * @return The sorted list of positive divisors. @@ -149,12 +144,12 @@ public class BigIntegerMath { */ @Deprecated static public Vector divisors(final BigInteger n) { - return (new Ifactor(n.abs())).divisors(); + return new Ifactor(n.abs()).divisors(); } /** * Evaluate sigma(n). - * + * * @param n * the argument for which divisors will be searched. * @return the sigma function. Sum of the divisors of the argument. @@ -162,12 +157,12 @@ public class BigIntegerMath { * @author Richard J. Mathar */ static public BigInteger sigma(final BigInteger n) { - return (new Ifactor(n.abs())).sigma().n; + return new Ifactor(n.abs()).sigma().n; } /** * Evaluate floor(sqrt(n)). - * + * * @param n * The non-negative argument. * @return The integer square root. The square root rounded down. @@ -175,16 +170,15 @@ public class BigIntegerMath { * @author Richard J. Mathar */ static public int isqrt(final int n) { - if (n < 0) { + if (n < 0) throw new ArithmeticException("Negative argument " + n); - } final double resul = Math.sqrt(n); return (int) Math.round(resul); } /** * Evaluate floor(sqrt(n)). - * + * * @param n * The non-negative argument. * Arguments less than zero throw an ArithmeticException. @@ -193,16 +187,15 @@ public class BigIntegerMath { * @author Richard J. Mathar */ static public long isqrt(final long n) { - if (n < 0) { + if (n < 0) throw new ArithmeticException("Negative argument " + n); - } final double resul = Math.sqrt(n); return Math.round(resul); } /** * Evaluate floor(sqrt(n)). - * + * * @param n * The non-negative argument. * Arguments less than zero throw an ArithmeticException. @@ -211,17 +204,16 @@ public class BigIntegerMath { * @author Richard J. Mathar */ static public BigInteger isqrt(final BigInteger n) { - if (n.compareTo(BigInteger.ZERO) < 0) { + if (n.compareTo(BigInteger.ZERO) < 0) throw new ArithmeticException("Negative argument " + n.toString()); - } /* * Start with an estimate from a floating point reduction. */ BigInteger x; final int bl = n.bitLength(); - if (bl > 120) { + if (bl > 120) x = n.shiftRight(bl / 2 - 1); - } else { + else { final double resul = Math.sqrt(n.doubleValue()); x = new BigInteger("" + Math.round(resul)); } @@ -233,13 +225,11 @@ public class BigIntegerMath { */ final BigInteger x2 = x.pow(2); BigInteger xplus2 = x.add(BigInteger.ONE).pow(2); - if (x2.compareTo(n) <= 0 && xplus2.compareTo(n) > 0) { + if (x2.compareTo(n) <= 0 && xplus2.compareTo(n) > 0) return x; - } xplus2 = xplus2.subtract(x.shiftLeft(2)); - if (xplus2.compareTo(n) <= 0 && x2.compareTo(n) > 0) { + if (xplus2.compareTo(n) <= 0 && x2.compareTo(n) > 0) return x.subtract(BigInteger.ONE); - } /* * Newton algorithm. This correction is on the * low side caused by the integer divisions. So the value required @@ -255,7 +245,7 @@ public class BigIntegerMath { * Evaluate core(n). * Returns the smallest positive integer m such that n/m is a perfect * square. - * + * * @param n * The non-negative argument. * @return The square-free part of n. @@ -263,16 +253,15 @@ public class BigIntegerMath { * @author Richard J. Mathar */ static public BigInteger core(final BigInteger n) { - if (n.compareTo(BigInteger.ZERO) < 0) { + if (n.compareTo(BigInteger.ZERO) < 0) throw new ArithmeticException("Negative argument " + n); - } final Ifactor i = new Ifactor(n); return i.core(); } /** * Minor of an integer matrix. - * + * * @param A * The matrix. * @param r @@ -291,40 +280,34 @@ public class BigIntegerMath { static public BigInteger[][] minor(final BigInteger[][] A, final int r, final int c) throws ArithmeticException { /* original row count */ final int rL = A.length; - if (rL == 0) { + if (rL == 0) throw new ArithmeticException("zero row count in matrix"); - } - if (r < 0 || r >= rL) { + if (r < 0 || r >= rL) throw new ArithmeticException("row number " + r + " out of range 0.." + (rL - 1)); - } /* original column count */ final int cL = A[0].length; - if (cL == 0) { + if (cL == 0) throw new ArithmeticException("zero column count in matrix"); - } - if (c < 0 || c >= cL) { + if (c < 0 || c >= cL) throw new ArithmeticException("column number " + c + " out of range 0.." + (cL - 1)); - } final BigInteger M[][] = new BigInteger[rL - 1][cL - 1]; int imrow = 0; - for (int row = 0; row < rL; row++) { + for (int row = 0; row < rL; row++) if (row != r) { int imcol = 0; - for (int col = 0; col < cL; col++) { + for (int col = 0; col < cL; col++) if (col != c) { M[imrow][imcol] = A[row][col]; imcol++; } - } imrow++; } - } return M; } /** * Replace column of a matrix with a column vector. - * + * * @param A * The matrix. * @param c @@ -344,38 +327,32 @@ public class BigIntegerMath { throws ArithmeticException { /* original row count */ final int rL = A.length; - if (rL == 0) { + if (rL == 0) throw new ArithmeticException("zero row count in matrix"); - } /* original column count */ final int cL = A[0].length; - if (cL == 0) { + if (cL == 0) throw new ArithmeticException("zero column count in matrix"); - } - if (c < 0 || c >= cL) { + if (c < 0 || c >= cL) throw new ArithmeticException("column number " + c + " out of range 0.." + (cL - 1)); - } final BigInteger M[][] = new BigInteger[rL][cL]; - for (int row = 0; row < rL; row++) { - for (int col = 0; col < cL; col++) { + for (int row = 0; row < rL; row++) + for (int col = 0; col < cL; col++) /* * currently, v may just be longer than the row count, and * surplus * elements will be ignored. Shorter v lead to an exception. */ - if (col != c) { + if (col != c) M[row][col] = A[row][col]; - } else { + else M[row][col] = v[row]; - } - } - } return M; } /** * Determinant of an integer square matrix. - * + * * @param A * The square matrix. * If column and row dimensions are unequal, an @@ -388,47 +365,42 @@ public class BigIntegerMath { BigInteger d = BigInteger.ZERO; /* row size */ final int rL = A.length; - if (rL == 0) { + if (rL == 0) throw new ArithmeticException("zero row count in matrix"); - } /* column size */ final int cL = A[0].length; - if (cL != rL) { + if (cL != rL) throw new ArithmeticException("Non-square matrix dim " + rL + " by " + cL); - } /* * Compute the low-order cases directly. */ - if (rL == 1) { + if (rL == 1) return A[0][0]; - } else if (rL == 2) { + else if (rL == 2) { d = A[0][0].multiply(A[1][1]); return d.subtract(A[0][1].multiply(A[1][0])); - } else { + } else /* Work arbitrarily along the first column of the matrix */ - for (int r = 0; r < rL; r++) { + for (int r = 0; r < rL; r++) /* * Do not consider minors that do no contribute anyway */ if (A[r][0].compareTo(BigInteger.ZERO) != 0) { - final BigInteger M[][] = minor(A, r, 0); - final BigInteger m = A[r][0].multiply(det(M)); + final BigInteger M[][] = BigIntegerMath.minor(A, r, 0); + final BigInteger m = A[r][0].multiply(BigIntegerMath.det(M)); /* recursive call */ - if (r % 2 == 0) { + if (r % 2 == 0) d = d.add(m); - } else { + else d = d.subtract(m); - } } - } - } return d; } /** * Solve a linear system of equations. - * + * * @param A * The square matrix. * If it is not of full rank, an ArithmeticException is thrown. @@ -444,18 +416,15 @@ public class BigIntegerMath { static public Rational[] solve(final BigInteger[][] A, final BigInteger[] rhs) throws ArithmeticException, Error { final int rL = A.length; - if (rL == 0) { + if (rL == 0) throw new ArithmeticException("zero row count in matrix"); - } /* column size */ final int cL = A[0].length; - if (cL != rL) { + if (cL != rL) throw new ArithmeticException("Non-square matrix dim " + rL + " by " + cL); - } - if (rhs.length != rL) { + if (rhs.length != rL) throw new ArithmeticException("Right hand side dim " + rhs.length + " unequal matrix dim " + rL); - } /* * Gauss elimination @@ -465,9 +434,8 @@ public class BigIntegerMath { /* * copy of r.h.s ito a mutable Rationalright hand side */ - for (int c = 0; c < cL; c++) { + for (int c = 0; c < cL; c++) x[c] = new Rational(rhs[c]); - } /* * Create zeros downwards column c by linear combination of row c and @@ -480,7 +448,7 @@ public class BigIntegerMath { */ if (A[c][c].compareTo(BigInteger.ZERO) == 0) { boolean swpd = false; - for (int r = c + 1; r < rL; r++) { + for (int r = c + 1; r < rL; r++) if (A[r][c].compareTo(BigInteger.ZERO) != 0) { for (int cpr = c; cpr < cL; cpr++) { final BigInteger tmp = A[c][cpr]; @@ -493,14 +461,12 @@ public class BigIntegerMath { swpd = true; break; } - } /* * not swapped with a non-zero row: determinant zero and no * solution */ - if (!swpd) { + if (!swpd) throw new ArithmeticException("Zero determinant of main matrix"); - } } /* create zero at A[c+1..cL-1][c] */ for (int r = c + 1; r < rL; r++) { @@ -516,15 +482,13 @@ public class BigIntegerMath { x[r] = tmp; } } - if (A[cL - 1][cL - 1].compareTo(BigInteger.ZERO) == 0) { + if (A[cL - 1][cL - 1].compareTo(BigInteger.ZERO) == 0) throw new ArithmeticException("Zero determinant of main matrix"); - } /* backward elimination */ for (int r = cL - 1; r >= 0; r--) { x[r] = x[r].divide(A[r][r]); - for (int rpr = r - 1; rpr >= 0; rpr--) { + for (int rpr = r - 1; rpr >= 0; rpr--) x[rpr] = x[rpr].subtract(x[r].multiply(A[rpr][r])); - } } return x; @@ -532,7 +496,7 @@ public class BigIntegerMath { /** * The lowest common multiple - * + * * @param a * The first argument * @param b @@ -548,7 +512,7 @@ public class BigIntegerMath { /** * Evaluate the value of an integer polynomial at some integer argument. - * + * * @param c * Represents the coefficients c[0]+c[1]*x+c[2]*x^2+.. of the * polynomial @@ -559,19 +523,17 @@ public class BigIntegerMath { * @author Richard J. Mathar */ static public BigInteger valueOf(final Vector c, final BigInteger x) { - if (c.size() == 0) { + if (c.size() == 0) return BigInteger.ZERO; - } BigInteger res = c.lastElement(); - for (int i = c.size() - 2; i >= 0; i--) { + for (int i = c.size() - 2; i >= 0; i--) res = res.multiply(x).add(c.elementAt(i)); - } return res; } /** * The central factorial number t(n,k) number at the indices provided. - * + * * @param n * the first parameter, non-negative. * @param k @@ -583,12 +545,12 @@ public class BigIntegerMath { * @see P. L. Butzer * et al, Num. Funct. Anal. Opt. 10 (5)( 1989) 419-488 */ - static public Rational centrlFactNumt(int n, int k) throws Error { - if (k > n || k < 0 || (k % 2) != (n % 2)) { + static public Rational centrlFactNumt(final int n, final int k) throws Error { + if (k > n || k < 0 || k % 2 != n % 2) return Rational.ZERO; - } else if (k == n) { + else if (k == n) return Rational.ONE; - } else { + else { /* Proposition 6.2.6 */ final Factorial f = new Factorial(); Rational jsum = new Rational(0, 1); @@ -598,28 +560,26 @@ public class BigIntegerMath { for (int nu = 0; nu <= j; nu++) { Rational t = new Rational(j - 2 * nu, 2); t = t.pow(kprime + j); - t = t.multiply(binomial(j, nu)); - if (nu % 2 != 0) { + t = t.multiply(BigIntegerMath.binomial(j, nu)); + if (nu % 2 != 0) nusum = nusum.subtract(t); - } else { + else nusum = nusum.add(t); - } } nusum = nusum.divide(f.at(j)).divide(n + j); - nusum = nusum.multiply(binomial(2 * kprime, kprime - j)); - if (j % 2 != 0) { + nusum = nusum.multiply(BigIntegerMath.binomial(2 * kprime, kprime - j)); + if (j % 2 != 0) jsum = jsum.subtract(nusum); - } else { + else jsum = jsum.add(nusum); - } } - return jsum.multiply(k).multiply(binomial(n + kprime, k)); + return jsum.multiply(k).multiply(BigIntegerMath.binomial(n + kprime, k)); } } /* CentralFactNumt */ /** * The central factorial number T(n,k) number at the indices provided. - * + * * @param n * the first parameter, non-negative. * @param k @@ -630,15 +590,14 @@ public class BigIntegerMath { * @see P. L. Butzer * et al, Num. Funct. Anal. Opt. 10 (5)( 1989) 419-488 */ - static public Rational centrlFactNumT(int n, int k) { - if (k > n || k < 0 || (k % 2) != (n % 2)) { + static public Rational centrlFactNumT(final int n, final int k) { + if (k > n || k < 0 || k % 2 != n % 2) return Rational.ZERO; - } else if (k == n) { + else if (k == n) return Rational.ONE; - } else { + else /* Proposition 2.1 */ - return centrlFactNumT(n - 2, k - 2).add(centrlFactNumT(n - 2, k).multiply(new Rational(k * k, 4))); - } + return BigIntegerMath.centrlFactNumT(n - 2, k - 2).add(BigIntegerMath.centrlFactNumT(n - 2, k).multiply(new Rational(k * k, 4))); } /* CentralFactNumT */ } /* BigIntegerMath */ diff --git a/core/src/main/java/org/nevec/rjm/BigIntegerPoly.java b/core/src/main/java/org/nevec/rjm/BigIntegerPoly.java index f82cc0f0..2ad7f008 100644 --- a/core/src/main/java/org/nevec/rjm/BigIntegerPoly.java +++ b/core/src/main/java/org/nevec/rjm/BigIntegerPoly.java @@ -12,7 +12,7 @@ import it.cavallium.warppi.util.Error; * Alternatively to be interpreted as a sequence which has the polynomial as an * (approximate) * generating function. - * + * * @since 2010-08-27 * @author Richard J. Mathar */ @@ -33,7 +33,7 @@ public class BigIntegerPoly implements Cloneable { /** * Ctor with a comma-separated list as the list of coefficients. - * + * * @param L * the string of the form a0,a1,a2,a3 with the coefficients */ @@ -41,16 +41,15 @@ public class BigIntegerPoly implements Cloneable { a = new Vector<>(); final Scanner sc = new Scanner(L); sc.useDelimiter(","); - while (sc.hasNextBigInteger()) { + while (sc.hasNextBigInteger()) a.add(sc.nextBigInteger()); - } simplify(); sc.close(); } /* ctor */ /** * Ctor with a list of coefficients. - * + * * @param c * The coefficients a0, a1, a2 etc in a0+a1*x+a2*x^2+... */ @@ -62,20 +61,19 @@ public class BigIntegerPoly implements Cloneable { /** * Ctor with a list of coefficients. - * + * * @param c * The coefficients a0, a1, a2 etc in a0+a1*x+a2*x^2+... */ public BigIntegerPoly(final BigInteger[] c) { - for (final BigInteger element : c) { + for (final BigInteger element : c) a.add(element.add(BigInteger.ZERO)); - } simplify(); } /* ctor */ /** * Create a copy of this. - * + * * @since 2010-08-27 */ @Override @@ -85,36 +83,34 @@ public class BigIntegerPoly implements Cloneable { /** * Translate into a RatPoly copy. - * + * * @since 2012-03-02 */ public RatPoly toRatPoly() { final RatPoly bd = new RatPoly(); - for (int i = 0; i < a.size(); i++) { + for (int i = 0; i < a.size(); i++) bd.set(i, a.elementAt(i)); - } return bd; } /* toRatPoly */ /** * Retrieve a polynomial coefficient. - * + * * @param n * the zero-based index of the coefficient. n=0 for the constant * term. * @return the polynomial coefficient in front of x^n. */ public BigInteger at(final int n) { - if (n < a.size()) { - return (a.elementAt(n)); - } else { - return (BigInteger.ZERO); - } + if (n < a.size()) + return a.elementAt(n); + else + return BigInteger.ZERO; } /* at */ /** * Evaluate at some integer argument. - * + * * @param x * The abscissa point of the evaluation * @return The polynomial value. @@ -122,34 +118,32 @@ public class BigIntegerPoly implements Cloneable { * @author Richard J. Mathar */ public BigInteger valueOf(final BigInteger x) { - if (a.size() == 0) { + if (a.size() == 0) return BigInteger.ZERO; - } BigInteger res = a.lastElement(); /* * Heron casted form */ - for (int i = a.size() - 2; i >= 0; i--) { + for (int i = a.size() - 2; i >= 0; i--) res = res.multiply(x).add(a.elementAt(i)); - } return res; } /* valueOf */ /** * Horner scheme to find the function value at the argument x - * + * * @param x * The argument x. * @return Value of the polynomial at x. * @since 2008-11-13 */ - public BigInteger valueOf(int x) { + public BigInteger valueOf(final int x) { return valueOf(new BigInteger("" + x)); } /* valueOf */ /** * Set a polynomial coefficient. - * + * * @param n * the zero-based index of the coefficient. n=0 for the constant * term. @@ -160,22 +154,21 @@ public class BigIntegerPoly implements Cloneable { * the new value of the coefficient. */ public void set(final int n, final BigInteger value) { - if (n < a.size()) { + if (n < a.size()) a.set(n, value); - } else { + else { /* * fill intermediate powers with coefficients of zero */ - while (a.size() < n) { + while (a.size() < n) a.add(BigInteger.ZERO); - } a.add(value); } } /* set */ /** * Set a polynomial coefficient. - * + * * @param n * the zero-based index of the coefficient. n=0 for the constant * term. @@ -192,7 +185,7 @@ public class BigIntegerPoly implements Cloneable { /** * Count of coefficients. - * + * * @return the number of polynomial coefficients. * Differs from the polynomial degree by one. */ @@ -202,7 +195,7 @@ public class BigIntegerPoly implements Cloneable { /** * Polynomial degree. - * + * * @return the polynomial degree. */ public int degree() { @@ -211,22 +204,20 @@ public class BigIntegerPoly implements Cloneable { /** * Polynomial lower degree. - * + * * @return power of the smallest non-zero coefficient. * If the polynomial is identical to 0, 0 is returned. */ public int ldegree() { - for (int n = 0; n < a.size(); n++) { - if (a.elementAt(n).compareTo(BigInteger.ZERO) != 0) { + for (int n = 0; n < a.size(); n++) + if (a.elementAt(n).compareTo(BigInteger.ZERO) != 0) return n; - } - } return 0; } /* ldegree */ /** * Multiply by a constant factor. - * + * * @param val * the factor * @return the product of this with the factor. @@ -236,17 +227,15 @@ public class BigIntegerPoly implements Cloneable { */ public BigIntegerPoly multiply(final BigInteger val) { final BigIntegerPoly resul = new BigIntegerPoly(); - if (val.compareTo(BigInteger.ZERO) != 0) { - for (int n = 0; n < a.size(); n++) { + if (val.compareTo(BigInteger.ZERO) != 0) + for (int n = 0; n < a.size(); n++) resul.set(n, a.elementAt(n).multiply(val)); - } - } return resul; } /* multiply */ /** * Multiply by another polynomial - * + * * @param val * the other polynomial * @return the product of this with the other polynomial @@ -259,9 +248,8 @@ public class BigIntegerPoly implements Cloneable { final int nmax = degree() + val.degree(); for (int n = 0; n <= nmax; n++) { BigInteger coef = BigInteger.ZERO; - for (int nleft = 0; nleft <= n; nleft++) { + for (int nleft = 0; nleft <= n; nleft++) coef = coef.add(at(nleft).multiply(val.at(n - nleft))); - } resul.set(n, coef); } resul.simplify(); @@ -270,19 +258,18 @@ public class BigIntegerPoly implements Cloneable { /** * Raise to a positive power. - * + * * @param n * the exponent of the power * @return the n-th power of this. */ public BigIntegerPoly pow(final int n) throws ArithmeticException { BigIntegerPoly resul = new BigIntegerPoly("1"); - if (n < 0) { + if (n < 0) throw new ArithmeticException("negative polynomial power " + n); - } else { - for (int i = 1; i <= n; i++) { + else { + for (int i = 1; i <= n; i++) resul = resul.multiply(this); - } resul.simplify(); return resul; } @@ -290,7 +277,7 @@ public class BigIntegerPoly implements Cloneable { /** * Add another polynomial - * + * * @param val * the other polynomial * @return the sum of this with the other polynomial @@ -302,7 +289,7 @@ public class BigIntegerPoly implements Cloneable { * the degree of the result is the larger of the two degrees (before * simplify() at least). */ - final int nmax = (degree() > val.degree()) ? degree() : val.degree(); + final int nmax = degree() > val.degree() ? degree() : val.degree(); for (int n = 0; n <= nmax; n++) { final BigInteger coef = at(n).add(val.at(n)); resul.set(n, coef); @@ -313,7 +300,7 @@ public class BigIntegerPoly implements Cloneable { /** * Subtract another polynomial - * + * * @param val * the other polynomial * @return the difference between this and the other polynomial @@ -325,7 +312,7 @@ public class BigIntegerPoly implements Cloneable { * the degree of the result is the larger of the two degrees (before * simplify() at least). */ - final int nmax = (degree() > val.degree()) ? degree() : val.degree(); + final int nmax = degree() > val.degree() ? degree() : val.degree(); for (int n = 0; n <= nmax; n++) { final BigInteger coef = at(n).subtract(val.at(n)); resul.set(n, coef); @@ -336,7 +323,7 @@ public class BigIntegerPoly implements Cloneable { /** * Divide by another polynomial. - * + * * @param val * the other polynomial * @return A vector with [0] containg the polynomial of degree which is the @@ -357,9 +344,8 @@ public class BigIntegerPoly implements Cloneable { /* * catch the case with val equal to zero */ - if (valSimpl.degree() == 0 && valSimpl.a.firstElement().compareTo(BigInteger.ZERO) == 0) { + if (valSimpl.degree() == 0 && valSimpl.a.firstElement().compareTo(BigInteger.ZERO) == 0) throw new ArithmeticException("Division through zero polynomial"); - } /* * degree of this smaller than degree of val: remainder is this */ @@ -377,9 +363,8 @@ public class BigIntegerPoly implements Cloneable { */ ret[0] = new BigIntegerPoly(); final BigInteger[] newc = thisSimpl.a.lastElement().divideAndRemainder(valSimpl.a.lastElement()); - if (newc[1].compareTo(BigInteger.ZERO) != 0) { + if (newc[1].compareTo(BigInteger.ZERO) != 0) throw new ArithmeticException("Incompatible leading term in " + this + " / " + val); - } ret[0].set(thisSimpl.degree() - valSimpl.degree(), newc[0]); /* @@ -392,9 +377,9 @@ public class BigIntegerPoly implements Cloneable { /* * any remainder left ? */ - if (ret[1].degree() < valSimpl.degree()) { + if (ret[1].degree() < valSimpl.degree()) ; - } else { + else { final BigIntegerPoly rem[] = ret[1].divideAndRemainder(val); ret[0] = ret[0].add(rem[0]); ret[1] = rem[1]; @@ -405,29 +390,26 @@ public class BigIntegerPoly implements Cloneable { /** * Print as a comma-separated list of coefficients. - * + * * @return the representation a0,a1,a2,a3,... * @since 2010-08-27 */ @Override public String toString() { String str = new String(); - for (int n = 0; n < a.size(); n++) { - if (n == 0) { + for (int n = 0; n < a.size(); n++) + if (n == 0) str += a.elementAt(n).toString(); - } else { + else str += "," + a.elementAt(n).toString(); - } - } - if (str.length() == 0) { + if (str.length() == 0) str = "0"; - } return str; } /* toString */ /** * Print as a polyomial in x. - * + * * @return The representation a0+a1*x+a2*x^2+... * The terms with zero coefficients are not mentioned. * @since 2008-10-26 @@ -438,21 +420,18 @@ public class BigIntegerPoly implements Cloneable { final BigInteger num = a.elementAt(n); if (num.compareTo(BigInteger.ZERO) != 0) { str += " "; - if (num.compareTo(BigInteger.ZERO) > 0 && n > 0) { + if (num.compareTo(BigInteger.ZERO) > 0 && n > 0) str += "+"; - } str += a.elementAt(n).toString(); if (n > 0) { str += "*x"; - if (n > 1) { + if (n > 1) str += "^" + n; - } } } } - if (str.length() == 0) { + if (str.length() == 0) str = "0"; - } return str; } /* toPString */ @@ -462,29 +441,27 @@ public class BigIntegerPoly implements Cloneable { */ protected void simplify() { int n = a.size() - 1; - if (n >= 0) { + if (n >= 0) while (a.elementAt(n).compareTo(BigInteger.ZERO) == 0) { a.removeElementAt(n); - if (--n < 0) { + if (--n < 0) break; - } } - } } /* simplify */ /** * First derivative. - * + * * @return The first derivative with respect to the indeterminate variable. * @since 2008-10-26 */ public BigIntegerPoly derive() { - if (a.size() <= 1) { + if (a.size() <= 1) /* * derivative of the constant is just zero */ return new BigIntegerPoly(); - } else { + else { final BigIntegerPoly d = new BigIntegerPoly(); for (int i = 1; i <= degree(); i++) { final BigInteger c = a.elementAt(i).multiply(new BigInteger("" + i)); @@ -496,39 +473,36 @@ public class BigIntegerPoly implements Cloneable { /** * Truncate polynomial degree. - * + * * @return The polynomial with all coefficients beyond deg set to zero. * @since 2010-08-27 */ - public BigIntegerPoly trunc(int newdeg) { + public BigIntegerPoly trunc(final int newdeg) { final BigIntegerPoly t = new BigIntegerPoly(); - for (int i = 0; i <= newdeg; i++) { + for (int i = 0; i <= newdeg; i++) t.set(i, at(i)); - } t.simplify(); return t; } /* trunc */ /** * Inverse Binomial transform. - * + * * @param maxdeg * the maximum polynomial degree of the result * @return the sequence of coefficients is the inverse binomial transform of * the original sequence. * @since 2010-08-29 */ - public BigIntegerPoly binomialTInv(int maxdeg) { + public BigIntegerPoly binomialTInv(final int maxdeg) { final BigIntegerPoly r = new BigIntegerPoly(); for (int i = 0; i <= maxdeg; i++) { BigInteger c = BigInteger.ZERO; - for (int j = 0; j <= i && j < a.size(); j++) { - if ((j + i) % 2 != 0) { + for (int j = 0; j <= i && j < a.size(); j++) + if ((j + i) % 2 != 0) c = c.subtract(a.elementAt(j).multiply(BigIntegerMath.binomial(i, j))); - } else { + else c = c.add(a.elementAt(j).multiply(BigIntegerMath.binomial(i, j))); - } - } r.set(i, c); } r.simplify(); @@ -537,7 +511,7 @@ public class BigIntegerPoly implements Cloneable { /** * Compute the order of the root r. - * + * * @return 1 for simple roots, 2 for order 2 etc., 0 if not a root * @since 2010-08-27 */ @@ -555,7 +529,7 @@ public class BigIntegerPoly implements Cloneable { /** * Generate the integer roots of the polynomial. - * + * * @return The vector of integer roots, without their multiplicity. * @since 2010-08-27 */ @@ -566,9 +540,8 @@ public class BigIntegerPoly implements Cloneable { /* * collect the zero */ - if (a.firstElement().compareTo(BigInteger.ZERO) == 0) { + if (a.firstElement().compareTo(BigInteger.ZERO) == 0) res.add(BigInteger.ZERO); - } /* * collect the divisors of the constant element (or the reduced @@ -582,14 +555,12 @@ public class BigIntegerPoly implements Cloneable { /* check the divisors (both signs) */ for (int i = 0; i < cand.size(); i++) { BigInteger roo = valueOf(cand.elementAt(i)); - if (roo.compareTo(BigInteger.ZERO) == 0) { + if (roo.compareTo(BigInteger.ZERO) == 0) /* found a root cand[i] */ res.add(cand.elementAt(i)); - } roo = valueOf(cand.elementAt(i).negate()); - if (roo.compareTo(BigInteger.ZERO) == 0) { + if (roo.compareTo(BigInteger.ZERO) == 0) res.add(cand.elementAt(i).negate()); - } } } return res; @@ -597,7 +568,7 @@ public class BigIntegerPoly implements Cloneable { /** * Generate the factors which are 2nd degree polynomials. - * + * * @return A (potentially empty) vector of factors, without multiplicity. * Only factors with non-zero absolute coefficient are generated. * This means the factors are of the form x^2+a*x+b=0 with nonzero @@ -611,9 +582,8 @@ public class BigIntegerPoly implements Cloneable { */ final Vector res = new Vector<>(); - if (degree() < 2) { + if (degree() < 2) return res; - } final BigInteger bsco = a.firstElement().abs(); @SuppressWarnings("deprecation") @@ -644,18 +614,18 @@ public class BigIntegerPoly implements Cloneable { * coefficient. * Solve z*(c*z+a)=-b or c*z+a = -b/z or -b/z-c*z = some integer a. */ - for (final BigComplex z : roo) { - for (final BigInteger bco : b) { - for (final BigInteger cco : c) { + for (final BigComplex z : roo) + for (final BigInteger bco : b) + for (final BigInteger cco : c) /* * the major reason to avoid the case b=0 is that this would * require precaution of double counting below. Note that * this * case is already covered by using iroots(). */ - if (bco.signum() != 0) { + if (bco.signum() != 0) for (int sig = -1; sig <= 1; sig += 2) { - final BigInteger bcosig = (sig > 0) ? bco : bco.negate(); + final BigInteger bcosig = sig > 0 ? bco : bco.negate(); /* * -a = b/z+c*z has real part b*Re(z)/|z|^2+c*Re(z) * = Re z *( b/|z|^2+c) @@ -675,34 +645,29 @@ public class BigIntegerPoly implements Cloneable { final BigIntegerPoly dtst = new BigIntegerPoly("" + bcosig + "," + a + "," + cco); try { final BigIntegerPoly[] rm = divideAndRemainder(dtst); - if (rm[1].isZero()) { + if (rm[1].isZero()) res.add(dtst); - } } catch (final ArithmeticException ex) {} } - } - } - } - } return res; } /* i2roots */ /** * Test whether this polynomial value is zero. - * + * * @return If this is a polynomial p(x)=0 for all x. */ public boolean isZero() { simplify(); - return (a.size() == 0); + return a.size() == 0; } /** * Factorization into integer polynomials. * The current factorization detects only factors which are polynomials of * order up to 2. - * + * * @return The vector of factors. Factors with higher multiplicity are * represented by repetition. * @throws Error @@ -732,32 +697,28 @@ public class BigIntegerPoly implements Cloneable { * collect factors which are polynomials of degree 2 */ final Vector pol2 = i2roots(); - for (final BigIntegerPoly i : pol2) { + for (final BigIntegerPoly i : pol2) /* * the internal loop catches cases with higher * powers of individual polynomials (of actual degree 2 or 4...) */ - while (res[0].degree() >= 2) { + while (res[0].degree() >= 2) try { final BigIntegerPoly[] dtst = res[0].divideAndRemainder(i); if (dtst[1].isZero()) { fac.add(i); res = dtst; - } else { + } else break; - } } catch (final ArithmeticException ex) { break; } - } - } /* * add remaining factor, if not equal to 1 */ - if (res[0].degree() > 0 || res[0].a.firstElement().compareTo(BigInteger.ONE) != 0) { + if (res[0].degree() > 0 || res[0].a.firstElement().compareTo(BigInteger.ONE) != 0) fac.add(res[0]); - } return fac; } /* ifactor */ diff --git a/core/src/main/java/org/nevec/rjm/BigSurd.java b/core/src/main/java/org/nevec/rjm/BigSurd.java index 3bb6d761..f252fef3 100644 --- a/core/src/main/java/org/nevec/rjm/BigSurd.java +++ b/core/src/main/java/org/nevec/rjm/BigSurd.java @@ -14,7 +14,7 @@ import it.cavallium.warppi.util.Utils; * a square root of a non-negative fraction. * This might be extended to values on the imaginary axis by allowing negative * values underneath the square root, but this is not yet implemented. - * + * * @since 2011-02-12 * @author Richard J. Mathar */ @@ -41,7 +41,7 @@ public class BigSurd implements Cloneable, Comparable { /** * Default ctor, which represents the zero. - * + * * @since 2011-02-12 */ public BigSurd() { @@ -52,21 +52,20 @@ public class BigSurd implements Cloneable, Comparable { /** * ctor given the prefactor and the basis of the root. * This creates an object of value a*sqrt(b). - * + * * @param a * the prefactor. * @param b * the discriminant. * @since 2011-02-12 */ - public BigSurd(Rational a, Rational b) { + public BigSurd(final Rational a, final Rational b) { pref = a; /* * reject attempts to use a negative b */ - if (b.signum() < 0) { + if (b.signum() < 0) throw new ProviderException("Not implemented: imaginary surds"); - } disc = b; try { normalize(); @@ -79,36 +78,36 @@ public class BigSurd implements Cloneable, Comparable { /** * ctor given the numerator and denominator of the root. * This creates an object of value sqrt(a/b). - * + * * @param a * the numerator * @param b * the denominator. * @since 2011-02-12 */ - public BigSurd(int a, int b) { + public BigSurd(final int a, final int b) { this(Rational.ONE, new Rational(a, b)); } /** * ctor given the value under the root. * This creates an object of value sqrt(a). - * + * * @param a * the discriminant. * @since 2011-02-12 */ - public BigSurd(BigInteger a) { + public BigSurd(final BigInteger a) { this(Rational.ONE, new Rational(a, BigInteger.ONE)); } - public BigSurd(Rational a) { + public BigSurd(final Rational a) { this(Rational.ONE, a); } /** * Create a deep copy. - * + * * @since 2011-02-12 */ @Override @@ -130,26 +129,25 @@ public class BigSurd implements Cloneable, Comparable { /** * Add two surds of compatible discriminant. - * + * * @param val * The value to be added to this. */ public BigSurdVec add(final BigSurd val) { // zero plus somethings yields something - if (signum() == 0) { + if (signum() == 0) return new BigSurdVec(val); - } else if (val.signum() == 0) { + else if (val.signum() == 0) return new BigSurdVec(this); - } else { + else // let the ctor of BigSurdVec to the work return new BigSurdVec(this, val); - } } /* BigSurd.add */ /** * Multiply by another square root. - * + * * @param val * a second number of this type. * @return the product of this with the val. @@ -161,7 +159,7 @@ public class BigSurd implements Cloneable, Comparable { /** * Multiply by a rational number. - * + * * @param val * the factor. * @return the product of this with the val. @@ -173,7 +171,7 @@ public class BigSurd implements Cloneable, Comparable { /** * Multiply by a BigInteger. - * + * * @param val * a second number. * @return the product of this with the value. @@ -185,7 +183,7 @@ public class BigSurd implements Cloneable, Comparable { /** * Multiply by an integer. - * + * * @param val * a second number. * @return the product of this with the value. @@ -198,7 +196,7 @@ public class BigSurd implements Cloneable, Comparable { /** * Compute the square. - * + * * @return this value squared. * @since 2011-02-12 */ @@ -210,7 +208,7 @@ public class BigSurd implements Cloneable, Comparable { /** * Divide by another square root. - * + * * @param val * A second number of this type. * @return The value of this/val @@ -218,9 +216,8 @@ public class BigSurd implements Cloneable, Comparable { * @since 2011-02-12 */ public BigSurd divide(final BigSurd val) throws Error { - if (val.signum() == 0) { + if (val.signum() == 0) throw new ArithmeticException("Dividing " + toFancyString() + " through zero."); - } return new BigSurd(pref.divide(val.pref), disc.divide(val.disc)); } /* BigSurd.divide */ @@ -228,14 +225,13 @@ public class BigSurd implements Cloneable, Comparable { final BigSurd bs = this; final BigInteger denominator = pref.b; String s = ""; - if (denominator.compareTo(BigInteger.ONE) != 0) { + if (denominator.compareTo(BigInteger.ONE) != 0) s += "("; - } - if (bs.isBigInteger()) { + if (bs.isBigInteger()) s += bs.BigDecimalValue(new MathContext(Utils.scale, Utils.scaleMode2)).toBigInteger().toString(); - } else if (bs.isRational()) { + else if (bs.isRational()) s += bs.toRational().toString(); - } else { + else { final BigInteger numerator = bs.pref.a; if (numerator.compareTo(BigInteger.ONE) != 0) { s += numerator.toString(); @@ -243,21 +239,19 @@ public class BigSurd implements Cloneable, Comparable { s += "("; } s += "2√"; - if (bs.disc.isInteger()) { + if (bs.disc.isInteger()) s += bs.disc.toString(); - } else { + else s += "(" + bs.disc.toString() + ")"; - } - if (numerator.compareTo(BigInteger.ONE) != 0) { + if (numerator.compareTo(BigInteger.ONE) != 0) s += ")"; - } } return s; } /** * Divide by an integer. - * + * * @param val * a second number. * @return the value of this/val @@ -265,31 +259,29 @@ public class BigSurd implements Cloneable, Comparable { * @since 2011-02-12 */ public BigSurd divide(final BigInteger val) throws Error { - if (val.signum() == 0) { + if (val.signum() == 0) throw new ArithmeticException("Dividing " + toFancyString() + " through zero."); - } return new BigSurd(pref.divide(val), disc); } /* BigSurd.divide */ /** * Divide by an integer. - * + * * @param val * A second number. * @return The value of this/val * @throws Error * @since 2011-02-12 */ - public BigSurd divide(int val) throws Error { - if (val == 0) { + public BigSurd divide(final int val) throws Error { + if (val == 0) throw new ArithmeticException("Dividing " + toFancyString() + " through zero."); - } return new BigSurd(pref.divide(val), disc); } /* BigSurd.divide */ /** * Compute the negative. - * + * * @return -this. * @since 2011-02-12 */ @@ -305,7 +297,7 @@ public class BigSurd implements Cloneable, Comparable { /** * Absolute value. - * + * * @return The absolute (non-negative) value of this. * @since 2011-02-12 */ @@ -315,7 +307,7 @@ public class BigSurd implements Cloneable, Comparable { /** * Compares the value of this with another constant. - * + * * @param val * the other constant to compare with * @return -1, 0 or 1 if this number is numerically less than, equal to, @@ -330,21 +322,16 @@ public class BigSurd implements Cloneable, Comparable { */ final int sig = signum(); final int sigv = val.signum(); - if (sig < 0 && sigv >= 0) { + if (sig < 0 && sigv >= 0) return -1; - } - if (sig > 0 && sigv <= 0) { + if (sig > 0 && sigv <= 0) return 1; - } - if (sig == 0 && sigv == 0) { + if (sig == 0 && sigv == 0) return 0; - } - if (sig == 0 && sigv > 0) { + if (sig == 0 && sigv > 0) return -1; - } - if (sig == 0 && sigv < 0) { + if (sig == 0 && sigv < 0) return 1; - } /* * Work out the cases of equal sign. Compare absolute values by @@ -355,34 +342,32 @@ public class BigSurd implements Cloneable, Comparable { final Rational this2 = sqr(); final Rational val2 = val.sqr(); final int c = this2.compareTo(val2); - if (c == 0) { + if (c == 0) return 0; - } else if (sig > 0 && c > 0 || sig < 0 && c < 0) { + else if (sig > 0 && c > 0 || sig < 0 && c < 0) return 1; - } else { + else return -1; - } } /* BigSurd.compareTo */ /** * Return a string in the format (number/denom)*()^(1/2). * If the discriminant equals 1, print just the prefactor. - * + * * @return the human-readable version in base 10 * @since 2011-02-12 */ @Override public String toString() { - if (disc.compareTo(Rational.ONE) != 0 && disc.compareTo(Rational.ZERO) != 0) { - return ("(" + pref.toString() + ")*(" + disc.toString() + ")^(1/2)"); - } else { + if (disc.compareTo(Rational.ONE) != 0 && disc.compareTo(Rational.ZERO) != 0) + return "(" + pref.toString() + ")*(" + disc.toString() + ")^(1/2)"; + else return pref.toString(); - } } /* BigSurd.toString */ /** * Return a double value representation. - * + * * @return The value with double precision. * @since 2011-02-12 */ @@ -395,24 +380,24 @@ public class BigSurd implements Cloneable, Comparable { System.out.println("dv sq " + p2.toString()); final double res = p2.doubleValue(); System.out.println("dv sq " + res); - return (pref.signum() >= 0) ? Math.sqrt(res) : -Math.sqrt(res); + return pref.signum() >= 0 ? Math.sqrt(res) : -Math.sqrt(res); } /* BigSurd.doubleValue */ /** * Return a float value representation. - * + * * @return The value with single precision. * @since 2011-02-12 */ public float floatValue() { - return (float) (doubleValue()); + return (float) doubleValue(); } /* BigSurd.floatValue */ /** * True if the value is integer. * Equivalent to the indication whether a conversion to an integer * can be exact. - * + * * @since 2011-02-12 */ public boolean isBigInteger() { @@ -423,29 +408,28 @@ public class BigSurd implements Cloneable, Comparable { * True if the value is rational. * Equivalent to the indication whether a conversion to a Rational can be * exact. - * + * * @since 2011-02-12 */ public boolean isRational() { - return (disc.signum() == 0 || disc.compareTo(Rational.ONE) == 0); + return disc.signum() == 0 || disc.compareTo(Rational.ONE) == 0; } /* BigSurd.isRational */ /** * Convert to a rational value if possible - * + * * @since 2012-02-15 */ public Rational toRational() { - if (isRational()) { + if (isRational()) return pref; - } else { + else throw new ArithmeticException("Undefined conversion " + toFancyString() + " to Rational."); - } } /* BigSurd.toRational */ /** * The sign: 1 if the number is >0, 0 if ==0, -1 if <0 - * + * * @return the signum of the value. * @since 2011-02-12 */ @@ -460,7 +444,7 @@ public class BigSurd implements Cloneable, Comparable { /** * Normalize to squarefree discriminant. - * + * * @throws Error * @since 2011-02-12 */ @@ -493,15 +477,14 @@ public class BigSurd implements Cloneable, Comparable { pref = pref.divide(sqf); disc = new Rational(numC, denC); - } else { + } else pref = Rational.ZERO; - } } /* BigSurd.normalize */ /** * Normalize to coprime numerator and denominator in prefactor and * discriminant - * + * * @throws Error * @since 2011-02-12 */ @@ -538,13 +521,13 @@ public class BigSurd implements Cloneable, Comparable { /** * Return the approximate floating point representation. - * + * * @param mc * Description of the accuracy needed. * @return A representation with digits valid as described by mc * @since 2012-02-15 */ - public BigDecimal BigDecimalValue(MathContext mc) { + public BigDecimal BigDecimalValue(final MathContext mc) { /* * the relative error of the result equals the relative error of the * prefactor plus half of the relative error of the discriminant. diff --git a/core/src/main/java/org/nevec/rjm/BigSurdVec.java b/core/src/main/java/org/nevec/rjm/BigSurdVec.java index dc75afbb..0a5ea5c0 100644 --- a/core/src/main/java/org/nevec/rjm/BigSurdVec.java +++ b/core/src/main/java/org/nevec/rjm/BigSurdVec.java @@ -12,7 +12,7 @@ import it.cavallium.warppi.util.Utils; * A BigSurdVec represents an algebraic sum or differences of values which each * term an instance of BigSurd. This mainly means that sums or differences of * two BigSurd (or two BigSurdVec) can be represented (exactly) as a BigSurdVec. - * + * * @since 2012-02-15 * @author Richard J. Mathar */ @@ -35,7 +35,7 @@ public class BigSurdVec implements Comparable { /** * Default ctor, which represents the zero. - * + * * @since 2012-02-15 */ public BigSurdVec() { @@ -44,26 +44,26 @@ public class BigSurdVec implements Comparable { /** * ctor given the value of a BigSurd. - * + * * @param a * The value to be represented by this vector. * @since 2012-02-15 */ - public BigSurdVec(BigSurd a) { + public BigSurdVec(final BigSurd a) { terms = new Vector<>(1); terms.add(a); } /* ctor */ /** * ctor given two values, which (when added) represent this number a+b. - * + * * @param a * The value to be represented by the first term of the vector. * @param b * The value to be represented by the second term of the vector. * @since 2012-02-15 */ - public BigSurdVec(BigSurd a, BigSurd b) { + public BigSurdVec(final BigSurd a, final BigSurd b) { terms = new Vector<>(2); terms.add(a); terms.add(b); @@ -78,18 +78,17 @@ public class BigSurdVec implements Comparable { /** * Combine terms that can be written as a single surd. This unites for * example the terms sqrt(90) and sqrt(10) to 4*sqrt(10). - * + * * @throws Error - * + * * @since 2012-02-15 */ protected void normalize() throws Error { /* * nothing to be done if at most one term */ - if (terms.size() <= 1) { + if (terms.size() <= 1) return; - } final Vector newter = new Vector<>(); newter.add(terms.firstElement()); @@ -113,9 +112,9 @@ public class BigSurdVec implements Comparable { /* * eliminate accidental zeros; overwrite with v*(1+r). */ - if (newpref.compareTo(Rational.ZERO) == 0) { + if (newpref.compareTo(Rational.ZERO) == 0) newter.removeElementAt(ex); - } else { + else { v = v.multiply(newpref); newter.setElementAt(v, ex); } @@ -126,9 +125,8 @@ public class BigSurdVec implements Comparable { /* * append if none of the existing elements matched */ - if (!merged) { + if (!merged) newter.add(todo); - } } /* overwrite old version */ @@ -138,14 +136,14 @@ public class BigSurdVec implements Comparable { /** * Compare algebraic value with oth. Returns -1, 0 or +1 depending on * whether this is smaller, equal to or larger than oth. - * + * * @param oth * The value with which this is to be compared. * @return 0 or +-1. * @since 2012-02-15 */ @Override - public int compareTo(BigSurdVec oth) { + public int compareTo(final BigSurdVec oth) { BigSurdVec diff; try { diff = this.subtract(oth); @@ -160,7 +158,7 @@ public class BigSurdVec implements Comparable { /** * Sign function. Returns -1, 0 or +1 depending on whether this is smaller, * equal to or larger than zero. - * + * * @return 0 or +-1. * @throws Error * @since 2012-02-15 @@ -170,16 +168,14 @@ public class BigSurdVec implements Comparable { * the case of zero is unique, because no (reduced) vector of surds * other than the one element 0 itself can add/subtract to zero. */ - if (terms.size() == 0) { + if (terms.size() == 0) return 0; - } /* * if there is one term: forward to the signum function of BigSurd */ - if (terms.size() == 1) { + if (terms.size() == 1) return terms.firstElement().signum(); - } /* * if all terms have a common sign: take that one offsig is the index of @@ -188,22 +184,18 @@ public class BigSurdVec implements Comparable { */ final int sig0 = terms.elementAt(0).signum(); int offsig = 1; - for (; offsig < terms.size(); offsig++) { - if (terms.elementAt(offsig).signum() != sig0) { + for (; offsig < terms.size(); offsig++) + if (terms.elementAt(offsig).signum() != sig0) break; - } - } - if (offsig >= terms.size()) { + if (offsig >= terms.size()) return sig0; - } /* * if there are two terms (now known to have different sign): forward to * the comparison of the two elements as BigSurds */ - if (terms.size() == 2) { + if (terms.size() == 2) return terms.elementAt(0).compareTo(terms.elementAt(1).negate()); - } /* * if there are three terms, move the one with the offending sign to the @@ -214,32 +206,30 @@ public class BigSurdVec implements Comparable { */ if (terms.size() == 3) { BigSurdVec lhs; - if (offsig == 2) { + if (offsig == 2) lhs = new BigSurdVec(terms.elementAt(0), terms.elementAt(1)); - } else { + else lhs = new BigSurdVec(terms.elementAt(0), terms.elementAt(2)); - } lhs = lhs.sqr(); /* * Strange line: this line isn't used, but it's present in this * code! - * - * - * + * + * + * * BigSurd rhs = new BigSurd(terms.elementAt(offsig).sqr(), * Rational.ONE); - * - * - * + * + * + * */ - if (lhs.compareTo(lhs) > 0) { + if (lhs.compareTo(lhs) > 0) /* * dominating sign was t(0)+t(offbar) */ return terms.elementAt(0).signum(); - } else { + else return terms.elementAt(offsig).signum(); - } } /* @@ -247,26 +237,25 @@ public class BigSurdVec implements Comparable { * with a small but correct number of digits, and resume with the sign * of that one. */ - return (floatValue() > 0.) ? 1 : -1; + return floatValue() > 0. ? 1 : -1; } /* signum */ /** * Construct an approximate floating point representation - * + * * @param mc * The intended accuracy of the result. * @return A truncated version with the precision described by mc */ - public BigDecimal BigDecimalValue(MathContext mc) { + public BigDecimal BigDecimalValue(final MathContext mc) { /* * simple cases with one term forwarded to the BigSurd class */ - if (terms.size() == 0) { + if (terms.size() == 0) return BigDecimal.ZERO; - } else if (terms.size() == 1) { + else if (terms.size() == 1) return terms.firstElement().BigDecimalValue(mc); - } /* * To reduce cancellation errors, loop over increasing local precision @@ -278,15 +267,13 @@ public class BigSurdVec implements Comparable { for (int addpr = 1;; addpr += 3) { final MathContext locmc = new MathContext(mc.getPrecision() + addpr, mc.getRoundingMode()); res[1] = BigDecimal.ZERO; - for (final BigSurd j : terms) { + for (final BigSurd j : terms) res[1] = BigDecimalMath.addRound(res[1], j.BigDecimalValue(locmc)); - } if (addpr > 1) { final BigDecimal err = res[1].subtract(res[0]).abs(); final int prec = BigDecimalMath.err2prec(res[1], err); - if (prec > mc.getPrecision()) { + if (prec > mc.getPrecision()) break; - } } res[0] = res[1]; } @@ -296,7 +283,7 @@ public class BigSurdVec implements Comparable { /** * Construct an approximate floating point representation - * + * * @return A truncated version with the precision described by mc */ public double doubleValue() { @@ -306,7 +293,7 @@ public class BigSurdVec implements Comparable { /** * Construct an approximate floating point representation - * + * * @return A truncated version with the precision described by mc */ public double floatValue() { @@ -316,7 +303,7 @@ public class BigSurdVec implements Comparable { /** * Add two vectors algebraically. - * + * * @param val * The value to be added to this. * @return The new value representing this+val. @@ -327,23 +314,19 @@ public class BigSurdVec implements Comparable { /* * concatenate the vectors and eliminate common overlaps */ - for (final BigSurd term : terms) { - if (term.compareTo(BigSurd.ZERO) != 0) { + for (final BigSurd term : terms) + if (term.compareTo(BigSurd.ZERO) != 0) sum.terms.add(term); - } - } - for (final BigSurd term : val.terms) { - if (term.compareTo(BigSurd.ZERO) != 0) { + for (final BigSurd term : val.terms) + if (term.compareTo(BigSurd.ZERO) != 0) sum.terms.add(term); - } - } sum.normalize(); return sum; } /* add */ /** * Add two vectors algebraically. - * + * * @param val * The value to be added to this. * @return The new value representing this+val. @@ -362,7 +345,7 @@ public class BigSurdVec implements Comparable { /** * Subtract another number. - * + * * @param val * The value to be subtracted from this. * @return The new value representing this-val. @@ -374,16 +357,15 @@ public class BigSurdVec implements Comparable { * concatenate the vectors and eliminate common overlaps */ sum.terms.addAll(terms); - for (final BigSurd s : val.terms) { + for (final BigSurd s : val.terms) sum.terms.add(s.negate()); - } sum.normalize(); return sum; } /* subtract */ /** * Subtract another number. - * + * * @param val * The value to be subtracted from this. * @return The new value representing this-val. @@ -402,7 +384,7 @@ public class BigSurdVec implements Comparable { /** * Compute the negative. - * + * * @return -this. * @since 2012-02-15 */ @@ -411,9 +393,8 @@ public class BigSurdVec implements Comparable { * accumulate the negated elements of term one by one */ final BigSurdVec resul = new BigSurdVec(); - for (final BigSurd s : terms) { + for (final BigSurd s : terms) resul.terms.add(s.negate()); - } /* * no normalization step here, because the negation of all terms does * not introduce new common factors @@ -423,7 +404,7 @@ public class BigSurdVec implements Comparable { /** * Compute the square. - * + * * @return this value squared. * @throws Error * @since 2012-02-15 @@ -434,21 +415,18 @@ public class BigSurdVec implements Comparable { * the mixed products. */ final BigSurdVec resul = new BigSurdVec(); - for (int i = 0; i < terms.size(); i++) { + for (int i = 0; i < terms.size(); i++) resul.terms.add(new BigSurd(terms.elementAt(i).sqr(), Rational.ONE)); - } - for (int i = 0; i < terms.size() - 1; i++) { - for (int j = i + 1; j < terms.size(); j++) { + for (int i = 0; i < terms.size() - 1; i++) + for (int j = i + 1; j < terms.size(); j++) resul.terms.add(terms.elementAt(i).multiply(terms.elementAt(j)).multiply(2)); - } - } resul.normalize(); return resul; } /* sqr */ /** * Multiply by another square root. - * + * * @param val * a second number of this type. * @return the product of this with the val. @@ -457,29 +435,25 @@ public class BigSurdVec implements Comparable { */ public BigSurdVec multiply(final BigSurd val) throws Error { final BigSurdVec resul = new BigSurdVec(); - for (final BigSurd s : terms) { + for (final BigSurd s : terms) resul.terms.add(s.multiply(val)); - } resul.normalize(); return resul; } /* multiply */ public BigSurdVec multiply(final BigSurdVec val) throws Error { BigSurdVec resul = new BigSurdVec(); - for (final BigSurd s : terms) { + for (final BigSurd s : terms) resul.terms.add(s); - } - for (final BigSurd s : val.terms) { + for (final BigSurd s : val.terms) resul = resul.multiply(s); - } return resul; } /* multiply */ public BigSurdVec divide(final BigSurd val) throws Error { final BigSurdVec resul = new BigSurdVec(); - for (final BigSurd s : terms) { + for (final BigSurd s : terms) resul.terms.add(s.divide(val)); - } resul.normalize(); return resul; } /* multiply */ @@ -487,25 +461,23 @@ public class BigSurdVec implements Comparable { public BigSurdVec divide(final BigSurdVec val) throws Error { BigSurdVec resul = new BigSurdVec(); resul.terms = terms; - for (final BigSurd s : val.terms) { + for (final BigSurd s : val.terms) resul = resul.divide(s); - } return resul; } /* divide */ /** * True if the value is rational. Equivalent to the indication whether a * conversion to a Rational can be exact. - * + * * @since 2011-02-12 */ public boolean isRational() { boolean val = false; for (final BigSurd s : terms) { val = s.isRational(); - if (val == false) { + if (val == false) break; - } } return val; } /* BigSurdVec.isRational */ @@ -513,69 +485,63 @@ public class BigSurdVec implements Comparable { /** * True if the value is BigInteger. Equivalent to the indication whether a * conversion to a BigInteger can be exact. - * + * * @since 2011-02-12 */ public boolean isBigInteger() { boolean val = false; for (final BigSurd s : terms) { val = s.isBigInteger(); - if (val == false) { + if (val == false) break; - } } return val; } /* BigSurdVec.isRational */ /** * Convert to a rational value if possible - * + * * @since 2012-02-15 */ public Rational toRational() { Rational rat = Rational.ZERO; - if (isRational() == false) { + if (isRational() == false) throw new ArithmeticException("Undefined conversion " + toString() + " to Rational."); - } - for (final BigSurd s : terms) { + for (final BigSurd s : terms) rat = rat.add(s.pref); - } return rat; } /* BigSurd.toRational */ /** * Convert to a BigInteger value if possible - * + * * @since 2012-02-15 */ public BigInteger toBigInteger() { BigDecimal tmp = BigDecimal.ZERO.setScale(Utils.scale, Utils.scaleMode); - if (isBigInteger() == false) { + if (isBigInteger() == false) throw new ArithmeticException("Undefined conversion " + toString() + " to Rational."); - } - for (final BigSurd s : terms) { + for (final BigSurd s : terms) tmp = BigDecimalMath.addRound(tmp, s.pref.BigDecimalValue(new MathContext(Utils.scale, Utils.scaleMode2))); - } return tmp.toBigInteger(); } /* BigSurd.toRational */ /** * Convert to a BigDecimal value if possible - * + * * @since 2012-02-15 */ public BigDecimal toBigDecimal() { BigDecimal tmp = BigDecimal.ZERO.setScale(Utils.scale, Utils.scaleMode); - for (final BigSurd s : terms) { + for (final BigSurd s : terms) tmp = BigDecimalMath.addRound(tmp, s.BigDecimalValue(new MathContext(Utils.scale, Utils.scaleMode2))); - } return tmp; } /* BigSurd.toBigDecimal */ /** * Return a string in the format (number/denom)*()^(1/2). If the * discriminant equals 1, print just the prefactor. - * + * * @return the human-readable version in base 10 * @since 2012-02-16 */ @@ -584,15 +550,14 @@ public class BigSurdVec implements Comparable { /* * simple cases with one term forwarded to the BigSurd class */ - if (terms.size() == 0) { + if (terms.size() == 0) return new String("0"); - } else { + else { String s = new String(); for (int t = 0; t < terms.size(); t++) { final BigSurd bs = terms.elementAt(t); - if (bs.signum() > 0) { + if (bs.signum() > 0) s += "+"; - } s += bs.toString(); } return s; @@ -600,27 +565,24 @@ public class BigSurdVec implements Comparable { } /* toString */ public String toFancyString() { - if (terms.size() == 0) { + if (terms.size() == 0) return new String("0"); - } else { + else { BigInteger denominator = BigInteger.ONE; - for (int i = 0; i < terms.size(); i++) { + for (int i = 0; i < terms.size(); i++) denominator = denominator.multiply(terms.elementAt(i).pref.b); - } String s = ""; - if (denominator.compareTo(BigInteger.ONE) != 0) { + if (denominator.compareTo(BigInteger.ONE) != 0) s += "("; - } for (int t = 0; t < terms.size(); t++) { final BigSurd bs = terms.elementAt(t); - if (bs.signum() > 0 && t > 0) { + if (bs.signum() > 0 && t > 0) s += "+"; - } - if (bs.isBigInteger()) { + if (bs.isBigInteger()) s += bs.BigDecimalValue(new MathContext(Utils.scale, Utils.scaleMode2)).toBigInteger().toString(); - } else if (bs.isRational()) { + else if (bs.isRational()) s += bs.toRational().toString(); - } else { + else { final BigInteger numerator = bs.pref.multiply(denominator).numer(); if (numerator.compareTo(BigInteger.ONE) != 0) { s += numerator.toString(); @@ -628,11 +590,10 @@ public class BigSurdVec implements Comparable { // s += "("; Radice quadrata. non servono le parentesi. } s += "Ⓐ"; - if (bs.disc.isInteger()) { + if (bs.disc.isInteger()) s += bs.disc.toString(); - } else { + else s += "(" + bs.disc.toString() + ")"; - } if (numerator.compareTo(BigInteger.ONE) != 0) { // s += ")"; Radice quadrata. non servono le parentesi. } diff --git a/core/src/main/java/org/nevec/rjm/Euler.java b/core/src/main/java/org/nevec/rjm/Euler.java index 76c1867d..7c127610 100644 --- a/core/src/main/java/org/nevec/rjm/Euler.java +++ b/core/src/main/java/org/nevec/rjm/Euler.java @@ -5,7 +5,7 @@ import java.util.Vector; /** * Euler numbers - * + * * @see A000364 in the OEIS. * @since 2008-10-30 * @author Richard J. Mathar @@ -20,54 +20,52 @@ public class Euler { * Ctor(). Fill the hash list initially with E_0 to E_3. */ public Euler() { - if (a.size() == 0) { - a.add(BigInteger.ONE); - a.add(BigInteger.ONE); - a.add(new BigInteger("5")); - a.add(new BigInteger("61")); + if (Euler.a.size() == 0) { + Euler.a.add(BigInteger.ONE); + Euler.a.add(BigInteger.ONE); + Euler.a.add(new BigInteger("5")); + Euler.a.add(new BigInteger("61")); } } /** * Compute a coefficient in the internal table. - * + * * @param n * the zero-based index of the coefficient. n=0 for the E_0 term. */ protected void set(final int n) { - while (n >= a.size()) { + while (n >= Euler.a.size()) { BigInteger val = BigInteger.ZERO; boolean sigPos = true; - final int thisn = a.size(); + final int thisn = Euler.a.size(); for (int i = thisn - 1; i > 0; i--) { - BigInteger f = new BigInteger("" + a.elementAt(i).toString()); + BigInteger f = new BigInteger("" + Euler.a.elementAt(i).toString()); f = f.multiply(BigIntegerMath.binomial(2 * thisn, 2 * i)); - if (sigPos) { + if (sigPos) val = val.add(f); - } else { + else val = val.subtract(f); - } sigPos = !sigPos; } - if (thisn % 2 == 0) { + if (thisn % 2 == 0) val = val.subtract(BigInteger.ONE); - } else { + else val = val.add(BigInteger.ONE); - } - a.add(val); + Euler.a.add(val); } } /** * The Euler number at the index provided. - * + * * @param n * the index, non-negative. * @return the E_0=E_1=1 , E_2=5, E_3=61 etc */ - public BigInteger at(int n) { + public BigInteger at(final int n) { set(n); - return (a.elementAt(n)); + return Euler.a.elementAt(n); } } /* Euler */ diff --git a/core/src/main/java/org/nevec/rjm/EulerPhi.java b/core/src/main/java/org/nevec/rjm/EulerPhi.java index 90032917..760db4b6 100644 --- a/core/src/main/java/org/nevec/rjm/EulerPhi.java +++ b/core/src/main/java/org/nevec/rjm/EulerPhi.java @@ -4,7 +4,7 @@ import java.math.BigInteger; /** * Euler totient function. - * + * * @see A000010 in the OEIS. * @since 2008-10-14 * @since 2012-03-04 Adapted to new Ifactor representation. @@ -19,35 +19,33 @@ public class EulerPhi { /** * Compute phi(n). - * + * * @param n * The positive argument of the function. * @return phi(n) */ - public BigInteger at(int n) { + public BigInteger at(final int n) { return at(new BigInteger("" + n)); } /* at */ /** * Compute phi(n). - * + * * @param n * The positive argument of the function. * @return phi(n) */ - public BigInteger at(BigInteger n) { - if (n.compareTo(BigInteger.ZERO) <= 0) { + public BigInteger at(final BigInteger n) { + if (n.compareTo(BigInteger.ZERO) <= 0) throw new ArithmeticException("negative argument " + n + " of EulerPhi"); - } final Ifactor prFact = new Ifactor(n); BigInteger phi = n; - if (n.compareTo(BigInteger.ONE) > 0) { + if (n.compareTo(BigInteger.ONE) > 0) for (int i = 0; i < prFact.primeexp.size(); i += 2) { final BigInteger p = new BigInteger(prFact.primeexp.elementAt(i).toString()); final BigInteger p_1 = p.subtract(BigInteger.ONE); phi = phi.multiply(p_1).divide(p); } - } return phi; } /* at */ @@ -55,12 +53,12 @@ public class EulerPhi { * Test program. * It takes one argument n and prints the value phi(n).
* java -cp . org.nevec.rjm.EulerPhi n
- * + * * @since 2006-08-14 */ - public static void main(String[] args) throws ArithmeticException { + public static void main(final String[] args) throws ArithmeticException { final EulerPhi a = new EulerPhi(); - final int n = (new Integer(args[0])).intValue(); + final int n = new Integer(args[0]).intValue(); System.out.println("phi(" + n + ") = " + a.at(n)); } } /* EulerPhi */ diff --git a/core/src/main/java/org/nevec/rjm/Factorial.java b/core/src/main/java/org/nevec/rjm/Factorial.java index 77c5d6c8..175bab0b 100644 --- a/core/src/main/java/org/nevec/rjm/Factorial.java +++ b/core/src/main/java/org/nevec/rjm/Factorial.java @@ -5,7 +5,7 @@ import java.util.Vector; /** * Factorials. - * + * * @since 2006-06-25 * @since 2012-02-15 Storage of the values based on Ifactor, not BigInteger. * @author Richard J. Mathar @@ -21,58 +21,58 @@ public class Factorial { * Initialize the vector of the factorials with 0!=1 and 1!=1. */ public Factorial() { - if (a.size() == 0) { - a.add(Ifactor.ONE); - a.add(Ifactor.ONE); + if (Factorial.a.size() == 0) { + Factorial.a.add(Ifactor.ONE); + Factorial.a.add(Ifactor.ONE); } } /* ctor */ /** * Compute the factorial of the non-negative integer. - * + * * @param n * the argument to the factorial, non-negative. * @return the factorial of n. */ - public BigInteger at(int n) { + public BigInteger at(final int n) { /* * extend the internal list if needed. */ growto(n); - return a.elementAt(n).n; + return Factorial.a.elementAt(n).n; } /* at */ /** * Compute the factorial of the non-negative integer. - * + * * @param n * the argument to the factorial, non-negative. * @return the factorial of n. */ - public Ifactor toIfactor(int n) { + public Ifactor toIfactor(final int n) { /* * extend the internal list if needed. */ growto(n); - return a.elementAt(n); + return Factorial.a.elementAt(n); } /* at */ /** * Extend the internal table to cover up to n! - * + * * @param n * The maximum factorial to be supported. * @since 2012-02-15 */ - private void growto(int n) { + private void growto(final int n) { /* * extend the internal list if needed. Size to be 2 for n<=1, 3 for n<=2 * etc. */ - while (a.size() <= n) { - final int lastn = a.size() - 1; + while (Factorial.a.size() <= n) { + final int lastn = Factorial.a.size() - 1; final Ifactor nextn = new Ifactor(lastn + 1); - a.add(a.elementAt(lastn).multiply(nextn)); + Factorial.a.add(Factorial.a.elementAt(lastn).multiply(nextn)); } } /* growto */ diff --git a/core/src/main/java/org/nevec/rjm/Harmonic.java b/core/src/main/java/org/nevec/rjm/Harmonic.java index a3f733df..6a159602 100644 --- a/core/src/main/java/org/nevec/rjm/Harmonic.java +++ b/core/src/main/java/org/nevec/rjm/Harmonic.java @@ -3,7 +3,7 @@ package org.nevec.rjm; /** * Harmonic numbers. * H(n) is the sum of the inverses of the integers from 1 to n. - * + * * @since 2008-10-19 * @author Richard J. Mathar */ @@ -16,16 +16,16 @@ public class Harmonic { /** * The Harmonic number at the index specified - * + * * @param n * the index, non-negative. * @return the H_1=1 for n=1, H_2=3/2 for n=2 etc. * For values of n less than 1, zero is returned. */ - public Rational at(int n) { - if (n < 1) { - return (new Rational(0, 1)); - } else { + public Rational at(final int n) { + if (n < 1) + return new Rational(0, 1); + else { /* * start with 1 as the result */ @@ -34,9 +34,8 @@ public class Harmonic { /* * add 1/i for i=2..n */ - for (int i = 2; i <= n; i++) { + for (int i = 2; i <= n; i++) a = a.add(new Rational(1, i)); - } return a; } } diff --git a/core/src/main/java/org/nevec/rjm/Ifactor.java b/core/src/main/java/org/nevec/rjm/Ifactor.java index 8b30ff32..f05b8f1c 100644 --- a/core/src/main/java/org/nevec/rjm/Ifactor.java +++ b/core/src/main/java/org/nevec/rjm/Ifactor.java @@ -10,7 +10,7 @@ import it.cavallium.warppi.util.Error; * Factored integers. * This class contains a non-negative integer with the prime factor * decomposition attached. - * + * * @since 2006-08-14 * @since 2012-02-14 The internal representation contains the bases, and becomes * sparser if few @@ -39,7 +39,7 @@ public class Ifactor implements Cloneable, Comparable { /** * Constructor given an integer. * constructor with an ordinary integer - * + * * @param number * the standard representation of the integer */ @@ -61,9 +61,8 @@ public class Ifactor implements Cloneable, Comparable { while (number % p == 0) { ex++; number /= p; - if (number == 1) { + if (number == 1) break; - } } if (ex > 0) { primeexp.add(new Integer(p)); @@ -81,7 +80,7 @@ public class Ifactor implements Cloneable, Comparable { * Constructor given a BigInteger . * Constructor with an ordinary integer, calling a prime factor * decomposition. - * + * * @param number * the BigInteger representation of the integer */ @@ -103,9 +102,8 @@ public class Ifactor implements Cloneable, Comparable { while (number.remainder(p).compareTo(BigInteger.ZERO) == 0) { ex++; number = number.divide(p); - if (number.compareTo(BigInteger.ONE) == 0) { + if (number.compareTo(BigInteger.ONE) == 0) break; - } } if (ex > 0) { primeexp.add(new Integer(p.intValue())); @@ -118,7 +116,7 @@ public class Ifactor implements Cloneable, Comparable { /** * Constructor given a list of exponents of the prime factor decomposition. - * + * * @param pows * the vector with the sorted list of exponents. * pows[0] is the exponent of 2, pows[1] the exponent of 3, @@ -126,7 +124,7 @@ public class Ifactor implements Cloneable, Comparable { * Note that this list does not include the primes, but assumes a * continuous prime-smooth basis. */ - public Ifactor(Vector pows) { + public Ifactor(final Vector pows) { primeexp = new Vector<>(2 * pows.size()); if (pows.size() > 0) { n = BigInteger.ONE; @@ -141,32 +139,31 @@ public class Ifactor implements Cloneable, Comparable { primeexp.add(new Integer(p.intValue())); primeexp.add(new Integer(ex)); } - } else { + } else n = BigInteger.ZERO; - } } /* Ifactor */ /** * Copy constructor. - * + * * @param oth * the value to be copied */ - public Ifactor(Ifactor oth) { + public Ifactor(final Ifactor oth) { n = oth.n; primeexp = oth.primeexp; } /* Ifactor */ /** * Deep copy. - * + * * @since 2009-08-14 */ @Override public Ifactor clone() { /* * Line not used: - * + * * Vector p = (Vector)primeexp.clone(); * */ @@ -180,18 +177,18 @@ public class Ifactor implements Cloneable, Comparable { * The value of this method is in allowing the Vector<>.contains() calls * that use the value, * not the reference for comparison. - * + * * @param oth * the number to compare this with. * @return true if both are the same numbers, false otherwise. */ public boolean equals(final Ifactor oth) { - return (n.compareTo(oth.n) == 0); + return n.compareTo(oth.n) == 0; } /* Ifactor.equals */ /** * Multiply with another positive integer. - * + * * @param oth * the second factor. * @return the product of both numbers. @@ -200,12 +197,12 @@ public class Ifactor implements Cloneable, Comparable { /* * the optimization is to factorize oth _before_ multiplying */ - return (multiply(new Ifactor(oth))); + return multiply(new Ifactor(oth)); } /* Ifactor.multiply */ /** * Multiply with another positive integer. - * + * * @param oth * the second factor. * @return the product of both numbers. @@ -214,12 +211,12 @@ public class Ifactor implements Cloneable, Comparable { /* * the optimization is to factorize oth _before_ multiplying */ - return (multiply(new Ifactor(oth))); + return multiply(new Ifactor(oth)); } /* Ifactor.multiply */ /** * Multiply with another positive integer. - * + * * @param oth * the second factor. * @return the product of both numbers. @@ -238,7 +235,7 @@ public class Ifactor implements Cloneable, Comparable { /** * Lowest common multiple of this with oth. - * + * * @param oth * the second parameter of lcm(this,oth) * @return the lowest common multiple of both numbers. Returns zero @@ -250,7 +247,7 @@ public class Ifactor implements Cloneable, Comparable { /** * Greatest common divisor of this and oth. - * + * * @param oth * the second parameter of gcd(this,oth) * @return the lowest common multiple of both numbers. Returns zero @@ -262,38 +259,38 @@ public class Ifactor implements Cloneable, Comparable { /** * Multiply with another positive integer. - * + * * @param oth * the second factor. * @param type * 0 to multiply, 1 for gcd, 2 for lcm * @return the product, gcd or lcm of both numbers. */ - protected Ifactor multGcdLcm(final Ifactor oth, int type) { + protected Ifactor multGcdLcm(final Ifactor oth, final int type) { final Ifactor prod = new Ifactor(0); /* * skip the case where 0*something =0, falling thru to the empty * representation for 0 */ - if (primeexp.size() != 0 && oth.primeexp.size() != 0) { + if (primeexp.size() != 0 && oth.primeexp.size() != 0) /* * Cases of 1 times something return something. * Cases of lcm(1, something) return something. * Cases of gcd(1, something) return 1. */ - if (primeexp.firstElement().intValue() == 1 && type == 0) { + if (primeexp.firstElement().intValue() == 1 && type == 0) return oth; - } else if (primeexp.firstElement().intValue() == 1 && type == 2) { + else if (primeexp.firstElement().intValue() == 1 && type == 2) return oth; - } else if (primeexp.firstElement().intValue() == 1 && type == 1) { + else if (primeexp.firstElement().intValue() == 1 && type == 1) return this; - } else if (oth.primeexp.firstElement().intValue() == 1 && type == 0) { + else if (oth.primeexp.firstElement().intValue() == 1 && type == 0) return this; - } else if (oth.primeexp.firstElement().intValue() == 1 && type == 2) { + else if (oth.primeexp.firstElement().intValue() == 1 && type == 2) return this; - } else if (oth.primeexp.firstElement().intValue() == 1 && type == 1) { + else if (oth.primeexp.firstElement().intValue() == 1 && type == 1) return oth; - } else { + else { int idxThis = 0; int idxOth = 0; switch (type) { @@ -315,7 +312,7 @@ public class Ifactor implements Cloneable, Comparable { * scan both representations left to right, increasing prime * powers */ - while (idxOth < oth.primeexp.size() || idxThis < primeexp.size()) { + while (idxOth < oth.primeexp.size() || idxThis < primeexp.size()) if (idxOth >= oth.primeexp.size()) { /* * exhausted the list in oth.primeexp; copy over the @@ -386,15 +383,13 @@ public class Ifactor implements Cloneable, Comparable { idxThis += 2; } } - } } - } return prod; } /* Ifactor.multGcdLcm */ /** * Integer division through another positive integer. - * + * * @param oth * the denominator. * @return the division of this through the oth, discarding the remainder. @@ -411,7 +406,7 @@ public class Ifactor implements Cloneable, Comparable { /** * Summation with another positive integer - * + * * @param oth * the other term. * @return the sum of both numbers @@ -420,16 +415,15 @@ public class Ifactor implements Cloneable, Comparable { /* * avoid refactorization if oth is zero... */ - if (oth.compareTo(BigInteger.ZERO) != 0) { + if (oth.compareTo(BigInteger.ZERO) != 0) return new Ifactor(n.add(oth)); - } else { + else return this; - } } /* Ifactor.add */ /** * Exponentiation with a positive integer. - * + * * @param exponent * the non-negative exponent * @return n^exponent. If exponent=0, the result is 1. @@ -438,13 +432,12 @@ public class Ifactor implements Cloneable, Comparable { /* * three simple cases first */ - if (exponent < 0) { + if (exponent < 0) throw new ArithmeticException("Cannot raise " + toString() + " to negative " + exponent); - } else if (exponent == 0) { + else if (exponent == 0) return new Ifactor(1); - } else if (exponent == 1) { + else if (exponent == 1) return this; - } /* * general case, the vector with the prime factor powers, which are @@ -463,7 +456,7 @@ public class Ifactor implements Cloneable, Comparable { /** * Pulling the r-th root. - * + * * @param r * the positive or negative (nonzero) root. * @return n^(1/r). @@ -474,9 +467,9 @@ public class Ifactor implements Cloneable, Comparable { * @since 2009-05-18 */ public Rational root(final int r) throws ArithmeticException, Error { - if (r == 0) { + if (r == 0) throw new ArithmeticException("Cannot pull zeroth root of " + toString()); - } else if (r < 0) { + else if (r < 0) { /* * a^(-1/b)= 1/(a^(1/b)) */ @@ -490,9 +483,8 @@ public class Ifactor implements Cloneable, Comparable { * stay in the range of rational results). */ final int ex = primeexp.elementAt(i + 1).intValue(); - if (ex % r != 0) { + if (ex % r != 0) throw new ArithmeticException("Cannot pull " + r + "th root of " + toString()); - } pows.multiply(new BigInteger("" + primeexp.elementAt(i)).pow(ex / r)); } @@ -506,7 +498,7 @@ public class Ifactor implements Cloneable, Comparable { /** * The set of positive divisors. - * + * * @return the vector of divisors of the absolute value, sorted. * @since 2010-08-27 */ @@ -519,9 +511,8 @@ public class Ifactor implements Cloneable, Comparable { * by 1 or by a product that contains the factors p1..py. */ final Vector d = new Vector<>(); - if (n.compareTo(BigInteger.ZERO) == 0) { + if (n.compareTo(BigInteger.ZERO) == 0) return d; - } d.add(BigInteger.ONE); if (n.compareTo(BigInteger.ONE) > 0) { /* Computes sigmaIncopml(p1^e*p2^e2...*py^ey) */ @@ -539,14 +530,12 @@ public class Ifactor implements Cloneable, Comparable { * the output contains all products of the form partd[]*pz^ez, ez>0, * and with the exception of the 1, all these are appended. */ - for (int i = 1; i < partd.size(); i++) { + for (int i = 1; i < partd.size(); i++) d.add(partd.elementAt(i)); - } for (int e = 1; e <= ez; e++) { final BigInteger pzez = pz.pow(e); - for (int i = 0; i < partd.size(); i++) { + for (int i = 0; i < partd.size(); i++) d.add(partd.elementAt(i).multiply(pzez)); - } } } Collections.sort(d); @@ -555,7 +544,7 @@ public class Ifactor implements Cloneable, Comparable { /** * Sum of the divisors of the number. - * + * * @return the sum of all divisors of the number, 1+....+n. */ public Ifactor sigma() { @@ -564,19 +553,19 @@ public class Ifactor implements Cloneable, Comparable { /** * Sum of the k-th powers of divisors of the number. - * + * * @return the sum of all divisors of the number, 1^k+....+n^k. */ - public Ifactor sigma(int k) { + public Ifactor sigma(final int k) { /* * the question is whether keeping a factorization is worth the effort * or whether one should simply multiply these to return a BigInteger... */ - if (n.compareTo(BigInteger.ONE) == 0) { - return ONE; - } else if (n.compareTo(BigInteger.ZERO) == 0) { - return ZERO; - } else { + if (n.compareTo(BigInteger.ONE) == 0) + return Ifactor.ONE; + else if (n.compareTo(BigInteger.ZERO) == 0) + return Ifactor.ZERO; + else { /* * multiplicative: sigma_k(p^e) = [p^(k*(e+1))-1]/[p^k-1] * sigma_0(p^e) = e+1. @@ -584,12 +573,12 @@ public class Ifactor implements Cloneable, Comparable { Ifactor resul = Ifactor.ONE; for (int i = 0; i < primeexp.size(); i += 2) { final int ex = primeexp.elementAt(i + 1).intValue(); - if (k == 0) { + if (k == 0) resul = resul.multiply(ex + 1); - } else { + else { final Integer p = primeexp.elementAt(i); - final BigInteger num = (new BigInteger(p.toString())).pow(k * (ex + 1)).subtract(BigInteger.ONE); - final BigInteger deno = (new BigInteger(p.toString())).pow(k).subtract(BigInteger.ONE); + final BigInteger num = new BigInteger(p.toString()).pow(k * (ex + 1)).subtract(BigInteger.ONE); + final BigInteger deno = new BigInteger(p.toString()).pow(k).subtract(BigInteger.ONE); /* * This division is of course exact, no remainder * The costly prime factorization is hidden here. @@ -608,7 +597,7 @@ public class Ifactor implements Cloneable, Comparable { * p3^e3*...*py^ey * pz^ez, * the value returned has the final factor pz^ez eliminated, which gives * p1^e1 * p2*e2* p3^e3*...*py^ey. - * + * * @return the new integer obtained by removing the highest prime power. * If this here represents 0 or 1, it is returned without change. * @since 2006-08-20 @@ -617,9 +606,8 @@ public class Ifactor implements Cloneable, Comparable { /* * the cases n==1 or n ==0 */ - if (n.compareTo(BigInteger.ONE) <= 0) { + if (n.compareTo(BigInteger.ONE) <= 0) return this; - } /* * The cases n>1 @@ -641,37 +629,34 @@ public class Ifactor implements Cloneable, Comparable { /** * Test whether this is a square of an integer (perfect square). - * + * * @return true if this is an integer squared (including 0), else false */ public boolean issquare() { /* * check the exponents, located at the odd-indexed positions */ - for (int i = 1; i < primeexp.size(); i += 2) { - if (primeexp.elementAt(i).intValue() % 2 != 0) { + for (int i = 1; i < primeexp.size(); i += 2) + if (primeexp.elementAt(i).intValue() % 2 != 0) return false; - } - } return true; } /* Ifactor.issquare */ /** * The sum of the prime factor exponents, with multiplicity. - * + * * @return the sum over the primeexp numbers */ public int bigomega() { int resul = 0; - for (int i = 1; i < primeexp.size(); i += 2) { + for (int i = 1; i < primeexp.size(); i += 2) resul += primeexp.elementAt(i).intValue(); - } - return (resul); + return resul; } /* Ifactor.bigomega */ /** * The sum of the prime factor exponents, without multiplicity. - * + * * @return the number of distinct prime factors. * @since 2008-10-16 */ @@ -681,17 +666,15 @@ public class Ifactor implements Cloneable, Comparable { /** * The square-free part. - * + * * @return the minimum m such that m times this number is a square. * @since 2008-10-16 */ public BigInteger core() { BigInteger resul = BigInteger.ONE; - for (int i = 0; i < primeexp.size(); i += 2) { - if (primeexp.elementAt(i + 1).intValue() % 2 != 0) { + for (int i = 0; i < primeexp.size(); i += 2) + if (primeexp.elementAt(i + 1).intValue() % 2 != 0) resul = resul.multiply(new BigInteger(primeexp.elementAt(i).toString())); - } - } return resul; } /* Ifactor.core */ @@ -700,91 +683,85 @@ public class Ifactor implements Cloneable, Comparable { * 1 if n=1, else, if k is the number of distinct prime factors, return * (-1)^k, * else, if k has repeated prime factors, return 0. - * + * * @return the moebius function. */ public int moebius() { - if (n.compareTo(BigInteger.ONE) <= 0) { + if (n.compareTo(BigInteger.ONE) <= 0) return 1; - } /* accumulate number of different primes in k */ int k = 1; for (int i = 0; i < primeexp.size(); i += 2) { final int e = primeexp.elementAt(i + 1).intValue(); - if (e > 1) { + if (e > 1) return 0; - } else if (e == 1) { + else if (e == 1) /* accumulates (-1)^k */ k *= -1; - } } - return (k); + return k; } /* Ifactor.moebius */ /** * Maximum of two values. - * + * * @param oth * the number to compare this with. * @return the larger of the two values. */ public Ifactor max(final Ifactor oth) { - if (n.compareTo(oth.n) >= 0) { + if (n.compareTo(oth.n) >= 0) return this; - } else { + else return oth; - } } /* Ifactor.max */ /** * Minimum of two values. - * + * * @param oth * the number to compare this with. * @return the smaller of the two values. */ public Ifactor min(final Ifactor oth) { - if (n.compareTo(oth.n) <= 0) { + if (n.compareTo(oth.n) <= 0) return this; - } else { + else return oth; - } } /* Ifactor.min */ /** * Maximum of a list of values. - * + * * @param set * list of numbers. * @return the largest in the list. */ public static Ifactor max(final Vector set) { Ifactor resul = set.elementAt(0); - for (int i = 1; i < set.size(); i++) { + for (int i = 1; i < set.size(); i++) resul = resul.max(set.elementAt(i)); - } return resul; } /* Ifactor.max */ /** * Minimum of a list of values. - * + * * @param set * list of numbers. * @return the smallest in the list. */ public static Ifactor min(final Vector set) { Ifactor resul = set.elementAt(0); - for (int i = 1; i < set.size(); i++) { + for (int i = 1; i < set.size(); i++) resul = resul.min(set.elementAt(i)); - } return resul; } /* Ifactor.min */ /** * Compare value against another Ifactor - * + * * @param oth * The value to be compared agains. * @return 1, 0 or -1 according to being larger, equal to or smaller than @@ -798,25 +775,23 @@ public class Ifactor implements Cloneable, Comparable { /** * Convert to printable format - * + * * @return a string of the form n:prime^pow*prime^pow*prime^pow... */ @Override public String toString() { String resul = new String(n.toString() + ":"); - if (n.compareTo(BigInteger.ONE) == 0) { + if (n.compareTo(BigInteger.ONE) == 0) resul += "1"; - } else { + else { boolean firstMul = true; for (int i = 0; i < primeexp.size(); i += 2) { - if (!firstMul) { + if (!firstMul) resul += "*"; - } - if (primeexp.elementAt(i + 1).intValue() > 1) { + if (primeexp.elementAt(i + 1).intValue() > 1) resul += primeexp.elementAt(i).toString() + "^" + primeexp.elementAt(i + 1).toString(); - } else { + else resul += primeexp.elementAt(i).toString(); - } firstMul = false; } } @@ -828,7 +803,7 @@ public class Ifactor implements Cloneable, Comparable { * It takes a single argument n and prints the integer factorizaton.
* java -cp . org.nevec.rjm.Ifactor n
*/ - public static void main(String[] args) throws Exception { + public static void main(final String[] args) throws Exception { final BigInteger n = new BigInteger(args[0]); System.out.println(new Ifactor(n)); } /* Ifactor.main */ diff --git a/core/src/main/java/org/nevec/rjm/PartitionsP.java b/core/src/main/java/org/nevec/rjm/PartitionsP.java index be05d656..a438acd1 100644 --- a/core/src/main/java/org/nevec/rjm/PartitionsP.java +++ b/core/src/main/java/org/nevec/rjm/PartitionsP.java @@ -5,7 +5,7 @@ import java.util.Vector; /** * Number of partitions. - * + * * @since 2008-10-15 * @author Richard J. Mathar */ @@ -24,65 +24,64 @@ public class PartitionsP { * Default constructor initializing a list of partitions up to 7. */ public PartitionsP() { - if (a.size() == 0) { - a.add(new BigInteger("" + 1)); - a.add(new BigInteger("" + 1)); - a.add(new BigInteger("" + 2)); - a.add(new BigInteger("" + 3)); - a.add(new BigInteger("" + 5)); - a.add(new BigInteger("" + 7)); + if (PartitionsP.a.size() == 0) { + PartitionsP.a.add(new BigInteger("" + 1)); + PartitionsP.a.add(new BigInteger("" + 1)); + PartitionsP.a.add(new BigInteger("" + 2)); + PartitionsP.a.add(new BigInteger("" + 3)); + PartitionsP.a.add(new BigInteger("" + 5)); + PartitionsP.a.add(new BigInteger("" + 7)); } - nMax = new BigInteger("" + (a.size() - 1)); + PartitionsP.nMax = new BigInteger("" + (PartitionsP.a.size() - 1)); } /* ctor */ /** * return the number of partitions of i - * + * * @param i * the zero-based index into the list of partitions * @return the ith partition number. This is 1 if i=0 or 1, 2 if i=2 and so * forth. */ - public BigInteger at(int i) { + public BigInteger at(final int i) { /* * If the current list is too small, increase in intervals * of 3 until the list has at least i elements. */ - while (i > nMax.intValue()) { - growto(nMax.add(new BigInteger("" + 3))); - } - return (a.elementAt(i)); + while (i > PartitionsP.nMax.intValue()) + growto(PartitionsP.nMax.add(new BigInteger("" + 3))); + return PartitionsP.a.elementAt(i); } /* at */ /** * extend the list of known partitions up to n - * + * * @param n * the maximum integer hashed after the call. */ - private void growto(BigInteger n) { - while (a.size() <= n.intValue()) { + private void growto(final BigInteger n) { + while (PartitionsP.a.size() <= n.intValue()) { BigInteger per = new BigInteger("0"); - final BigInteger cursiz = new BigInteger("" + a.size()); - for (int k = 0; k < a.size(); k++) { - final BigInteger tmp = a.elementAt(k).multiply(BigIntegerMath.sigma(a.size() - k)); + final BigInteger cursiz = new BigInteger("" + PartitionsP.a.size()); + for (int k = 0; k < PartitionsP.a.size(); k++) { + final BigInteger tmp = PartitionsP.a.elementAt(k).multiply(BigIntegerMath.sigma(PartitionsP.a.size() - k)); per = per.add(tmp); } - a.add(per.divide(cursiz)); + PartitionsP.a.add(per.divide(cursiz)); } - nMax = new BigInteger("" + (a.size() - 1)); + PartitionsP.nMax = new BigInteger("" + (PartitionsP.a.size() - 1)); } /* growto */ /** * Test program. * It takes one integer argument n and prints P(n).
* java -cp . org.nevec.rjm.PartitionsP n
- * + * * @since 2008-10-15 */ - public static void main(String[] args) throws Exception { + public static void main(final String[] args) throws Exception { final PartitionsP a = new PartitionsP(); - final int n = (new Integer(args[0])).intValue(); + final int n = new Integer(args[0]).intValue(); System.out.println("P(" + n + ")=" + a.at(n)); } } diff --git a/core/src/main/java/org/nevec/rjm/Prime.java b/core/src/main/java/org/nevec/rjm/Prime.java index b5c9a541..710f945b 100644 --- a/core/src/main/java/org/nevec/rjm/Prime.java +++ b/core/src/main/java/org/nevec/rjm/Prime.java @@ -13,7 +13,7 @@ import java.util.Vector; * may easily require all available memory and stall finally, because indeed * a dense list of primes with growing upper bound is kept without any hashing * or lagging scheme. - * + * * @since 2006-08-11 * @author Richard J. Mathar */ @@ -35,26 +35,26 @@ public class Prime { * action. */ public Prime() { - if (a.size() == 0) { - a.add(new BigInteger("" + 2)); - a.add(new BigInteger("" + 3)); - a.add(new BigInteger("" + 5)); - a.add(new BigInteger("" + 7)); - a.add(new BigInteger("" + 11)); - a.add(new BigInteger("" + 13)); - a.add(new BigInteger("" + 17)); + if (Prime.a.size() == 0) { + Prime.a.add(new BigInteger("" + 2)); + Prime.a.add(new BigInteger("" + 3)); + Prime.a.add(new BigInteger("" + 5)); + Prime.a.add(new BigInteger("" + 7)); + Prime.a.add(new BigInteger("" + 11)); + Prime.a.add(new BigInteger("" + 13)); + Prime.a.add(new BigInteger("" + 17)); } - nMax = a.lastElement(); + Prime.nMax = Prime.a.lastElement(); } /** * Test if a number is a prime. - * + * * @param n * the integer to be tested for primality * @return true if prime, false if not */ - public boolean contains(BigInteger n) { + public boolean contains(final BigInteger n) { /* * not documented * return ( n.isProbablePrime() ) ; @@ -66,12 +66,12 @@ public class Prime { return true; } growto(n); - return (a.contains(n)); + return Prime.a.contains(n); } /** * Test whether a number n is a strong pseudoprime to base a. - * + * * @param n * the integer to be tested for primality * @param a @@ -86,13 +86,13 @@ public class Prime { /* * numbers less than 2 are not prime */ - if (n.compareTo(two) == -1) { + if (n.compareTo(two) == -1) return false; - } else if (n.compareTo(two) == 0) { + else if (n.compareTo(two) == 0) return true; - } else if (n.remainder(two).compareTo(BigInteger.ZERO) == 0) { + else if (n.remainder(two).compareTo(BigInteger.ZERO) == 0) return false; - } else { + else { /* * q= n- 1 = d *2^s with d odd */ @@ -103,25 +103,22 @@ public class Prime { /* * test whether a^d = 1 (mod n) */ - if (a.modPow(d, n).compareTo(BigInteger.ONE) == 0) { + if (a.modPow(d, n).compareTo(BigInteger.ONE) == 0) return true; - } /* * test whether a^(d*2^r) = -1 (mod n), 0<=r= a.size()) { - growto(nMax.add(new BigInteger("" + 5))); - } - return (a.elementAt(i)); + while (i >= Prime.a.size()) + growto(Prime.nMax.add(new BigInteger("" + 5))); + return Prime.a.elementAt(i); } /** * return the count of primes <= n - * + * * @param n * the upper limit of the scan * @return the ith prime. This is 2 if i=0, 3 if i=1 and so forth. */ - public BigInteger pi(BigInteger n) { + public BigInteger pi(final BigInteger n) { /* * If the current list is too small, increase in intervals * of 5 until the list has at least i elements. */ growto(n); BigInteger r = new BigInteger("0"); - for (int i = 0; i < a.size(); i++) { - if (a.elementAt(i).compareTo(n) <= 0) { + for (int i = 0; i < Prime.a.size(); i++) + if (Prime.a.elementAt(i).compareTo(n) <= 0) r = r.add(BigInteger.ONE); - } - } return r; } /** * return the smallest prime larger than n - * + * * @param n * lower limit of the search * @return the next larger prime. * @since 2008-10-16 */ - public BigInteger nextprime(BigInteger n) { + public BigInteger nextprime(final BigInteger n) { /* if n <=1, return 2 */ - if (n.compareTo(BigInteger.ONE) <= 0) { - return (a.elementAt(0)); - } + if (n.compareTo(BigInteger.ONE) <= 0) + return Prime.a.elementAt(0); /* * If the currently largest element in the list is too small, increase * in intervals * of 5 until the list has at least i elements. */ - while (a.lastElement().compareTo(n) <= 0) { - growto(nMax.add(new BigInteger("" + 5))); - } - for (int i = 0; i < a.size(); i++) { - if (a.elementAt(i).compareTo(n) == 1) { - return (a.elementAt(i)); - } - } - return (a.lastElement()); + while (Prime.a.lastElement().compareTo(n) <= 0) + growto(Prime.nMax.add(new BigInteger("" + 5))); + for (int i = 0; i < Prime.a.size(); i++) + if (Prime.a.elementAt(i).compareTo(n) == 1) + return Prime.a.elementAt(i); + return Prime.a.lastElement(); } /** * return the largest prime smaller than n - * + * * @param n * upper limit of the search * @return the next smaller prime. * @since 2008-10-17 */ - public BigInteger prevprime(BigInteger n) { + public BigInteger prevprime(final BigInteger n) { /* if n <=2, return 0 */ - if (n.compareTo(BigInteger.ONE) <= 0) { + if (n.compareTo(BigInteger.ONE) <= 0) return BigInteger.ZERO; - } /* * If the currently largest element in the list is too small, increase * in intervals * of 5 until the list has at least i elements. */ - while (a.lastElement().compareTo(n) < 0) { - growto(nMax.add(new BigInteger("" + 5))); - } + while (Prime.a.lastElement().compareTo(n) < 0) + growto(Prime.nMax.add(new BigInteger("" + 5))); - for (int i = 0; i < a.size(); i++) { - if (a.elementAt(i).compareTo(n) >= 0) { - return (a.elementAt(i - 1)); - } - } - return (a.lastElement()); + for (int i = 0; i < Prime.a.size(); i++) + if (Prime.a.elementAt(i).compareTo(n) >= 0) + return Prime.a.elementAt(i - 1); + return Prime.a.lastElement(); } /** * extend the list of known primes up to n - * + * * @param n * the maximum integer known to be prime or not prime after the * call. */ - protected void growto(BigInteger n) { - while (nMax.compareTo(n) == -1) { - nMax = nMax.add(BigInteger.ONE); + protected void growto(final BigInteger n) { + while (Prime.nMax.compareTo(n) == -1) { + Prime.nMax = Prime.nMax.add(BigInteger.ONE); boolean isp = true; - for (int p = 0; p < a.size(); p++) { + for (int p = 0; p < Prime.a.size(); p++) { /* * Test the list of known primes only up to sqrt(n) */ - if (a.get(p).multiply(a.get(p)).compareTo(nMax) == 1) { + if (Prime.a.get(p).multiply(Prime.a.get(p)).compareTo(Prime.nMax) == 1) break; - } /* * The next case means that the p'th number in the list of known * primes divides * nMax and nMax cannot be a prime. */ - if (nMax.remainder(a.get(p)).compareTo(BigInteger.ZERO) == 0) { + if (Prime.nMax.remainder(Prime.a.get(p)).compareTo(BigInteger.ZERO) == 0) { isp = false; break; } } - if (isp) { - a.add(nMax); - } + if (isp) + Prime.a.add(Prime.nMax); } } @@ -303,16 +283,15 @@ public class Prime { * Usage: java -cp . org.nevec.rjm.Prime n
* This takes a single argument (n) and prints prime(n), the previous and * next prime, and pi(n). - * + * * @since 2006-08-14 */ - public static void main(String[] args) throws Exception { + public static void main(final String[] args) throws Exception { final Prime a = new Prime(); - final int n = (new Integer(args[0])).intValue(); + final int n = new Integer(args[0]).intValue(); if (n >= 1) { - if (n >= 2) { + if (n >= 2) System.out.println("prime(" + (n - 1) + ") = " + a.at(n - 1)); - } System.out.println("prime(" + n + ") = " + a.at(n)); System.out.println("prime(" + (n + 1) + ") = " + a.at(n + 1)); System.out.println("pi(" + n + ") = " + a.pi(new BigInteger("" + n))); diff --git a/core/src/main/java/org/nevec/rjm/RatPoly.java b/core/src/main/java/org/nevec/rjm/RatPoly.java index 4f9392b5..ecaf04bb 100644 --- a/core/src/main/java/org/nevec/rjm/RatPoly.java +++ b/core/src/main/java/org/nevec/rjm/RatPoly.java @@ -14,7 +14,7 @@ import it.cavallium.warppi.util.Error; * Alternatively to be interpreted as a sequence which has the polynomial as an * (approximate) * generating function. - * + * * @since 2006-06-25 * @author Richard J. Mathar */ @@ -36,22 +36,21 @@ class RatPoly { /** * Constructor with an explicit list of coefficients. - * + * * @param L * the coefficients a0, a1, a2, a3,.., A deep copy of the these * is created. */ public RatPoly(final Vector L) { a = new Vector<>(); - for (int i = 0; i < L.size(); i++) { + for (int i = 0; i < L.size(); i++) a.add(L.elementAt(i).clone()); - } simplify(); } /* ctor */ /** * Constructor with a comma-separated list as the list of coefficients. - * + * * @param L * the string of the form a0,a1,a2,a3 with the coefficients */ @@ -69,7 +68,7 @@ class RatPoly { /** * Constructor from a hypergeometric series. - * + * * @param A * the list of values in the numerator of AFB * @param B @@ -79,7 +78,7 @@ class RatPoly { * @throws Error * @since 2008-11-13 */ - public RatPoly(final Vector A, final Vector B, int nmax) throws Error { + public RatPoly(final Vector A, final Vector B, final int nmax) throws Error { /* * To allow common initialization with the signature below, * the main body is assembled in a separate function. @@ -89,7 +88,7 @@ class RatPoly { /** * Constructor from a hypergeometric series. - * + * * @param A * the list of values in the numerator of AFB. * At least one of these values must be a negative integer, which @@ -102,18 +101,14 @@ class RatPoly { */ public RatPoly(final Vector A, final Vector B) throws Error { BigInteger Nmax = BigInteger.ONE.negate(); - for (int j = 0; j < A.size(); j++) { - if (A.elementAt(j).compareTo(BigInteger.ZERO) <= 0) { - if (Nmax.compareTo(BigInteger.ZERO) < 0) { + for (int j = 0; j < A.size(); j++) + if (A.elementAt(j).compareTo(BigInteger.ZERO) <= 0) + if (Nmax.compareTo(BigInteger.ZERO) < 0) Nmax = A.elementAt(j).negate(); - } else { + else Nmax = Nmax.min(A.elementAt(j).negate()); - } - } - } - if (Nmax.compareTo(BigInteger.ZERO) < 0) { + if (Nmax.compareTo(BigInteger.ZERO) < 0) throw new ArithmeticException("Infinite Number of Terms in Series " + Nmax.toString()); - } final int nmax = Nmax.intValue() - 1; init(A, B, nmax); @@ -121,7 +116,7 @@ class RatPoly { /** * Constructor from a hypergeometric series. - * + * * @param A * the list of values in the numerator of AFB * @param B @@ -131,7 +126,7 @@ class RatPoly { * @throws Error * @since 2008-11-13 */ - protected void init(final Vector A, final Vector B, int nmax) throws Error { + protected void init(final Vector A, final Vector B, final int nmax) throws Error { a = new Vector<>(); final Factorial f = new Factorial(); for (int n = 0; n <= nmax; n++) { @@ -152,7 +147,7 @@ class RatPoly { /** * Create a copy of this. - * + * * @since 2008-11-07 */ @Override @@ -165,103 +160,99 @@ class RatPoly { /** * Retrieve a polynomial coefficient. - * + * * @param n * the zero-based index of the coefficient. n=0 for the constant * term. * @return the polynomial coefficient in front of x^n. */ public Rational at(final int n) { - if (n < a.size()) { - return (a.elementAt(n)); - } else { - return (new Rational(0, 1)); - } + if (n < a.size()) + return a.elementAt(n); + else + return new Rational(0, 1); } /* at */ /** * Horner scheme to find the function value at the argument x - * + * * @param x * The argument of the polynomial * @param mc * The context determining the precision of the value returned. * @since 2008-10-26 */ - public BigComplex valueOf(BigComplex x, MathContext mc) { + public BigComplex valueOf(final BigComplex x, final MathContext mc) { /* result is initialized to zero */ BigComplex f = new BigComplex(); - for (int i = degree(); i >= 0; i--) { + for (int i = degree(); i >= 0; i--) f = f.multiply(x, mc).add(a.elementAt(i).BigDecimalValue(mc)); - } return f; } /* valueOf */ /** * Horner scheme to find the function value at the argument x - * + * * @param x * The argument of the polynomial * @since 2008-11-13 */ - public Rational valueOf(Rational x) { + public Rational valueOf(final Rational x) { /* result is initialized to zero */ Rational f = new Rational(0, 1); - for (int i = degree(); i >= 0; i--) { + for (int i = degree(); i >= 0; i--) f = f.multiply(x).add(a.elementAt(i)); - } return f; } /* valueOf */ /** * Horner scheme to find the function value at the argument x - * + * * @param x * The argument of the polynomial * @since 2008-11-13 */ - public Rational valueOf(int x) { + public Rational valueOf(final int x) { return valueOf(new Rational(x, 1)); } /* valueOf */ /** * Horner scheme to evaluate the function at the argument x - * + * * @param x * The argument of the polynomial * @since 2010-08-27 */ - public Rational valueOf(BigInteger x) { + public Rational valueOf(final BigInteger x) { return valueOf(new Rational(x)); } /* valueOf */ /* * Set a polynomial coefficient. - * + * * @param n the zero-based index of the coefficient. n=0 for the constant * term. * If the polynomial has not yet the degree to need this coefficient, * the intermediate coefficients are implicitly set to zero. - * + * * @param value the new value of the coefficient. */ public void set(final int n, final Rational value) { - if (n < a.size()) { + if (n < a.size()) a.set(n, value); - } else { + else { /* * fill intermediate powers with coefficients of zero */ - while (a.size() < n) { + while (a.size() < n) a.add(new Rational(0, 1)); - } a.add(value); } } /* set */ /** * Set a polynomial coefficient. - * + * * @param n * the zero-based index of the coefficient. n=0 for the constant * term. @@ -278,7 +269,7 @@ class RatPoly { /** * Set a polynomial coefficient. - * + * * @param n * the zero-based index of the coefficient. n=0 for the constant * term. @@ -295,15 +286,14 @@ class RatPoly { /* * Set to the taylor series of exp(x) up to degree nmax. - * + * * @param nmax the maximum polynomial degree */ public void setExp(final int nmax) { a.clear(); final Factorial factorial = new Factorial(); - for (int n = 0; n <= nmax; n++) { + for (int n = 0; n <= nmax; n++) set(n, new Rational(BigInteger.ONE, factorial.at(n))); - } } /* setExp */ /** @@ -319,7 +309,7 @@ class RatPoly { /** * Count of coefficients. One more than the degree of the polynomial. - * + * * @return the number of polynomial coefficients. */ public int size() { @@ -328,7 +318,7 @@ class RatPoly { /** * Polynomial degree. - * + * * @return the polynomial degree. */ public int degree() { @@ -337,24 +327,22 @@ class RatPoly { /** * Lower Polynomial degree. - * + * * @return The smallest exponent n such that [x^n] of the polynomial is * nonzero. * If the polynmial is identical zero, the result is (still) 0. * @since 2010-08-27 */ public int ldegree() { - for (int n = 0; n < a.size(); n++) { - if (a.elementAt(n).compareTo(BigInteger.ZERO) != 0) { + for (int n = 0; n < a.size(); n++) + if (a.elementAt(n).compareTo(BigInteger.ZERO) != 0) return n; - } - } return 0; } /* ldegree */ /** * Multiply by a constant factor. - * + * * @param val * the factor * @return the product of this with the factor. @@ -363,17 +351,15 @@ class RatPoly { */ public RatPoly multiply(final Rational val) { final RatPoly resul = new RatPoly(); - if (val.compareTo(BigInteger.ZERO) != 0) { - for (int n = 0; n < a.size(); n++) { + if (val.compareTo(BigInteger.ZERO) != 0) + for (int n = 0; n < a.size(); n++) resul.set(n, a.elementAt(n).multiply(val)); - } - } return resul; } /* multiply */ /** * Multiply by a constant factor. - * + * * @param val * the factor * @return the product of this with the factor. @@ -383,17 +369,15 @@ class RatPoly { */ public RatPoly multiply(final BigInteger val) { final RatPoly resul = new RatPoly(); - if (val.compareTo(BigInteger.ZERO) != 0) { - for (int n = 0; n < a.size(); n++) { + if (val.compareTo(BigInteger.ZERO) != 0) + for (int n = 0; n < a.size(); n++) resul.set(n, a.elementAt(n).multiply(val)); - } - } return resul; } /* multiply */ /** * Multiply by another polynomial - * + * * @param val * the other polynomial * @return the product of this with the other polynomial @@ -406,9 +390,8 @@ class RatPoly { final int nmax = degree() + val.degree(); for (int n = 0; n <= nmax; n++) { Rational coef = new Rational(0, 1); - for (int nleft = 0; nleft <= n; nleft++) { + for (int nleft = 0; nleft <= n; nleft++) coef = coef.add(at(nleft).multiply(val.at(n - nleft))); - } resul.set(n, coef); } resul.simplify(); @@ -417,23 +400,22 @@ class RatPoly { /** * Raise to a positive power. - * + * * @param n * The non-negative exponent of the power * @return The n-th power of this. */ public RatPoly pow(final int n) throws ArithmeticException { RatPoly resul = new RatPoly("1"); - if (n < 0) { + if (n < 0) throw new ArithmeticException("negative polynomial power " + n); - } else { + else { /* * this ought probably be done with some binary representation * of the power and a smaller number of multiplications. */ - for (int i = 1; i <= n; i++) { + for (int i = 1; i <= n; i++) resul = resul.multiply(this); - } resul.simplify(); return resul; } @@ -444,7 +426,7 @@ class RatPoly { * The result is the taylor expansion of this, truncated at the first * term that remains undetermined based on the current number of * coefficients. - * + * * @param r * the exponent of the power * @return This^r . @@ -485,7 +467,7 @@ class RatPoly { /** * Add another polynomial - * + * * @param val * The other polynomial * @return The sum of this and the other polynomial @@ -497,7 +479,7 @@ class RatPoly { * the degree of the result is the larger of the two degrees (before * simplify() at least). */ - final int nmax = (degree() > val.degree()) ? degree() : val.degree(); + final int nmax = degree() > val.degree() ? degree() : val.degree(); for (int n = 0; n <= nmax; n++) { final Rational coef = at(n).add(val.at(n)); resul.set(n, coef); @@ -508,7 +490,7 @@ class RatPoly { /** * Subtract another polynomial - * + * * @param val * The other polynomial * @return The difference between this and the other polynomial @@ -520,7 +502,7 @@ class RatPoly { * the degree of the result is the larger of the two degrees (before * simplify() at least). */ - final int nmax = (degree() > val.degree()) ? degree() : val.degree(); + final int nmax = degree() > val.degree() ? degree() : val.degree(); for (int n = 0; n <= nmax; n++) { final Rational coef = at(n).subtract(val.at(n)); resul.set(n, coef); @@ -531,7 +513,7 @@ class RatPoly { /** * Divide by a constant. - * + * * @param val * the constant through which the coefficients will be divided. * @return the Taylor expansion of this/val . @@ -541,18 +523,16 @@ class RatPoly { public RatPoly divide(final Rational val) throws Error { if (val.compareTo(Rational.ZERO) != 0) { final RatPoly resul = new RatPoly(); - for (int n = 0; n < a.size(); n++) { + for (int n = 0; n < a.size(); n++) resul.set(n, a.elementAt(n).divide(val)); - } return resul; - } else { + } else throw new ArithmeticException("Cannot divide " + toPString() + " through zero."); - } } /* divide */ /** * Divide by another polynomial. - * + * * @param val * the other polynomial * @param nmax @@ -560,7 +540,7 @@ class RatPoly { * @return the Taylor expansion of this/val up to degree nmax. * @throws Error */ - public RatPoly divide(final RatPoly val, int nmax) throws Error { + public RatPoly divide(final RatPoly val, final int nmax) throws Error { final RatPoly num = this; final RatPoly denom = val; @@ -570,9 +550,8 @@ class RatPoly { while (num.at(0).compareTo(BigInteger.ZERO) == 0 && denom.at(0).compareTo(BigInteger.ZERO) == 0) { num.a.remove(0); denom.a.remove(0); - if (num.size() <= 1 || denom.size() <= 1) { + if (num.size() <= 1 || denom.size() <= 1) break; - } } final RatPoly resul = new RatPoly(); @@ -582,19 +561,18 @@ class RatPoly { */ for (int n = 0; n <= nmax; n++) { Rational coef = num.at(n); - for (int nres = 0; nres < n; nres++) { + for (int nres = 0; nres < n; nres++) coef = coef.subtract(resul.at(nres).multiply(denom.at(n - nres))); - } coef = coef.divide(denom.at(0)); resul.set(n, coef); } resul.simplify(); - return (resul); + return resul; } /* divide */ /** * Divide by another polynomial. - * + * * @param val * the other polynomial * @return A vector with [0] containg the polynomial of degree which is the @@ -617,9 +595,8 @@ class RatPoly { /* * catch the case with val equal to zero */ - if (valSimpl.degree() == 0 && valSimpl.a.firstElement().compareTo(Rational.ZERO) == 0) { + if (valSimpl.degree() == 0 && valSimpl.a.firstElement().compareTo(Rational.ZERO) == 0) throw new ArithmeticException("Division through zero polynomial"); - } /* * degree of this smaller than degree of val: remainder is this */ @@ -647,9 +624,9 @@ class RatPoly { /* * any remainder left ? */ - if (ret[1].degree() < valSimpl.degree()) { + if (ret[1].degree() < valSimpl.degree()) ; - } else { + else { final RatPoly rem[] = ret[1].divideAndRemainder(val); ret[0] = ret[0].add(rem[0]); ret[1] = rem[1]; @@ -660,7 +637,7 @@ class RatPoly { /** * Print as a comma-separated list of coefficients. - * + * * @return The representation a0,a1,a2,a3,... * This is a sort of opposite of the ctor that takes a string as an * argument. @@ -669,25 +646,22 @@ class RatPoly { @Override public String toString() { String str = new String(); - for (int n = 0; n < a.size(); n++) { - if (n == 0) { + for (int n = 0; n < a.size(); n++) + if (n == 0) str += a.elementAt(n).toString(); - } else { + else str += "," + a.elementAt(n).toString(); - } - } /* * print at least a sole zero */ - if (str.length() == 0) { + if (str.length() == 0) str = "0"; - } return str; } /* toString */ /** * Print as a polyomial in x. - * + * * @return To representation a0+a1*x+a2*x^2+... * This does not print the terms with coefficients equal to zero. * @since 2008-10-26 @@ -698,24 +672,21 @@ class RatPoly { final BigInteger num = a.elementAt(n).a; if (num.compareTo(BigInteger.ZERO) != 0) { str += " "; - if (num.compareTo(BigInteger.ZERO) > 0) { + if (num.compareTo(BigInteger.ZERO) > 0) str += "+"; - } str += a.elementAt(n).toString(); if (n > 0) { str += "*x"; - if (n > 1) { + if (n > 1) str += "^" + n; - } } } } /* * print at least a sole zero */ - if (str.length() == 0) { + if (str.length() == 0) str = "0"; - } return str; } /* toPString */ @@ -727,29 +698,27 @@ class RatPoly { */ private void simplify() { int n = a.size() - 1; - if (n >= 0) { + if (n >= 0) while (a.elementAt(n).compareTo(BigInteger.ZERO) == 0) { a.remove(n); - if (--n < 0) { + if (--n < 0) break; - } } - } } /* simplify */ /** * First derivative. - * + * * @return The first derivative with respect to the indeterminate variable. * @since 2008-10-26 */ public RatPoly derive() { - if (a.size() <= 1) { + if (a.size() <= 1) /* * derivative of the constant is just zero */ return new RatPoly(); - } else { + else { final RatPoly d = new RatPoly(); for (int i = 1; i <= degree(); i++) { final Rational c = a.elementAt(i).multiply(i); @@ -762,7 +731,7 @@ class RatPoly { /** * Scale coefficients such that the coefficient in front of the maximum * degree is unity. - * + * * @return The scaled polynomial * @throws Error * @since 2008-10-26 @@ -779,26 +748,25 @@ class RatPoly { /** * Mobius transform. - * + * * @param maxdeg * the maximum polynomial degree of the result * @return the sequence of coefficients is the Mobius transform of the * original sequence. * @since 2008-12-02 */ - public RatPoly mobiusT(int maxdeg) { + public RatPoly mobiusT(final int maxdeg) { /* * Start with the polynomial 0 */ final RatPoly r = new RatPoly(); for (int i = 1; i <= maxdeg; i++) { Rational c = new Rational(); - for (int d = 1; d <= i && d < a.size(); d++) { + for (int d = 1; d <= i && d < a.size(); d++) if (i % d == 0) { final Ifactor m = new Ifactor(i / d); c = c.add(a.elementAt(d).multiply(m.moebius())); } - } r.set(i, c); } r.simplify(); @@ -807,25 +775,23 @@ class RatPoly { /** * Inverse Mobius transform. - * + * * @param maxdeg * the maximum polynomial degree of the result * @return the sequence of coefficients is the inverse Mobius transform of * the original sequence. * @since 2008-12-02 */ - public RatPoly mobiusTInv(int maxdeg) { + public RatPoly mobiusTInv(final int maxdeg) { /* * Start with the polynomial 0 */ final RatPoly r = new RatPoly(); for (int i = 1; i <= maxdeg; i++) { Rational c = new Rational(); - for (int d = 1; d <= i && d < a.size(); d++) { - if (i % d == 0) { + for (int d = 1; d <= i && d < a.size(); d++) + if (i % d == 0) c = c.add(a.elementAt(d)); - } - } r.set(i, c); } r.simplify(); @@ -834,20 +800,19 @@ class RatPoly { /** * Binomial transform. - * + * * @param maxdeg * the maximum polynomial degree of the result * @return the sequence of coefficients is the binomial transform of the * original sequence. * @since 2008-10-26 */ - public RatPoly binomialT(int maxdeg) { + public RatPoly binomialT(final int maxdeg) { final RatPoly r = new RatPoly(); for (int i = 0; i <= maxdeg; i++) { Rational c = new Rational(0, 1); - for (int j = 0; j <= i && j < a.size(); j++) { + for (int j = 0; j <= i && j < a.size(); j++) c = c.add(a.elementAt(j).multiply(BigIntegerMath.binomial(i, j))); - } r.set(i, c); } r.simplify(); @@ -856,24 +821,22 @@ class RatPoly { /** * Inverse Binomial transform. - * + * * @param maxdeg * the maximum polynomial degree of the result * @return the sequence of coefficients is the inverse binomial transform of * the original sequence. * @since 2008-10-26 */ - public RatPoly binomialTInv(int maxdeg) { + public RatPoly binomialTInv(final int maxdeg) { final RatPoly r = new RatPoly(); for (int i = 0; i <= maxdeg; i++) { Rational c = new Rational(0, 1); - for (int j = 0; j <= i && j < a.size(); j++) { - if ((j + i) % 2 != 0) { + for (int j = 0; j <= i && j < a.size(); j++) + if ((j + i) % 2 != 0) c = c.subtract(a.elementAt(j).multiply(BigIntegerMath.binomial(i, j))); - } else { + else c = c.add(a.elementAt(j).multiply(BigIntegerMath.binomial(i, j))); - } - } r.set(i, c); } r.simplify(); @@ -882,7 +845,7 @@ class RatPoly { /** * Truncate polynomial degree. - * + * * @param newdeg * The maximum degree of the result. * @return The polynomial with all coefficients beyond deg set to zero. @@ -894,18 +857,17 @@ class RatPoly { * than this. * @since 2008-10-26 */ - public RatPoly trunc(int newdeg) { + public RatPoly trunc(final int newdeg) { final RatPoly t = new RatPoly(); - for (int i = 0; i <= newdeg; i++) { + for (int i = 0; i <= newdeg; i++) t.set(i, at(i)); - } t.simplify(); return t; } /* trunc */ /** * Generate the roots of the polynomial in floating point arithmetic. - * + * * @see Durand * Kerner method * @param the @@ -913,7 +875,7 @@ class RatPoly { * @throws Error * @since 2008-10-26 */ - public Vector roots(int digits) throws Error { + public Vector roots(final int digits) throws Error { final RatPoly mon = monic(); final Random rand = new Random(); @@ -926,9 +888,8 @@ class RatPoly { for (int i = 0; i <= d; i++) { /* scale coefficient at maximum degree */ final double absi = Math.abs(mon.at(i).doubleValue()); - if (absi > randRad) { + if (absi > randRad) randRad = absi; - } } randRad += 1.0; @@ -958,23 +919,19 @@ class RatPoly { */ BigComplex thisx = res.elementAt(v); BigComplex nv = mon.valueOf(thisx, mc); - for (int j = 0; j < d; j++) { - if (j != v) { + for (int j = 0; j < d; j++) + if (j != v) nv = nv.divide(thisx.subtract(res.elementAt(j)), mc); - } - } /* is this value converged ? */ - if (nv.abs(mc).doubleValue() > thisx.abs(mc).doubleValue() * Math.pow(10.0, -digits)) { + if (nv.abs(mc).doubleValue() > thisx.abs(mc).doubleValue() * Math.pow(10.0, -digits)) convr = false; - } thisx = thisx.subtract(nv); /* If unstable, start over */ - if (thisx.abs(MathContext.DECIMAL32).doubleValue() > randRad) { + if (thisx.abs(MathContext.DECIMAL32).doubleValue() > randRad) return roots(digits); - } resPlus.add(thisx); } @@ -986,7 +943,7 @@ class RatPoly { /** * Generate the integer roots of the polynomial. - * + * * @return The vector of integer roots, with multiplicity. * The shows alternatingly first a root then its multiplicty, then * another root and multiplicty etc. @@ -1012,9 +969,8 @@ class RatPoly { * start with denominator of first non-zero coefficient. */ BigInteger lcmDeno = a.elementAt(lowd).b; - for (int i = lowd + 1; i < degree(); i++) { + for (int i = lowd + 1; i < degree(); i++) lcmDeno = BigIntegerMath.lcm(lcmDeno, a.elementAt(i).b); - } /* * and eventually get the integer polynomial by ignoring the diff --git a/core/src/main/java/org/nevec/rjm/Rational.java b/core/src/main/java/org/nevec/rjm/Rational.java index 962345fa..f28c1734 100644 --- a/core/src/main/java/org/nevec/rjm/Rational.java +++ b/core/src/main/java/org/nevec/rjm/Rational.java @@ -11,7 +11,7 @@ import it.cavallium.warppi.util.Errors; /** * Fractions (rational numbers). They are divisions of two BigInteger numbers, * reduced to coprime numerator and denominator. - * + * * @since 2006-06-25 * @author Richard J. Mathar */ @@ -28,7 +28,7 @@ public class Rational implements Cloneable, Comparable { /** * The maximum and minimum value of a standard Java integer, 2^31. - * + * * @since 2009-05-18 */ static public BigInteger MAX_INT = new BigInteger("2147483647"); @@ -45,14 +45,14 @@ public class Rational implements Cloneable, Comparable { /** * The constant 1/2 - * + * * @since 2010-05-25 */ static public Rational HALF = new Rational(1, 2); /** * Default ctor, which represents the zero. - * + * * @since 2007-11-17 */ public Rational() { @@ -62,13 +62,13 @@ public class Rational implements Cloneable, Comparable { /** * ctor from a numerator and denominator. - * + * * @param a * the numerator. * @param b * the denominator. */ - public Rational(BigInteger a, BigInteger b) { + public Rational(final BigInteger a, final BigInteger b) { this.a = a; this.b = b; normalize(); @@ -76,54 +76,54 @@ public class Rational implements Cloneable, Comparable { /** * ctor from a numerator. - * + * * @param a * the BigInteger. */ - public Rational(BigInteger a) { + public Rational(final BigInteger a) { this.a = a; b = new BigInteger("1"); } /** * ctor from a numerator and denominator. - * + * * @param a * the numerator. * @param b * the denominator. */ - public Rational(int a, int b) { + public Rational(final int a, final int b) { this(new BigInteger("" + a), new BigInteger("" + b)); } /** * ctor from an integer. - * + * * @param n * the integer to be represented by the new instance. * @since 2010-07-18 */ - public Rational(int n) { + public Rational(final int n) { this(n, 1); } /** * ctor from a string representation. - * + * * @param str * the string. This either has a slash in it, separating two * integers, or, if there is no slash, is representing the * numerator with implicit denominator equal to 1. Warning: this * does not yet test for a denominator equal to zero */ - public Rational(String str) { + public Rational(final String str) { this(str, 10); } /** * ctor from a string representation in a specified base. - * + * * @param str * the string. This either has a slash in it, separating two * integers, or, if there is no slash, is just representing the @@ -132,7 +132,7 @@ public class Rational implements Cloneable, Comparable { * the number base for numerator and denominator Warning: this * does not yet test for a denominator equal to zero */ - public Rational(String str, int radix) { + public Rational(final String str, final int radix) { final int hasslah = str.indexOf("/"); if (hasslah == -1) { a = new BigInteger(str, radix); @@ -150,7 +150,7 @@ public class Rational implements Cloneable, Comparable { /** * Create a copy. - * + * * @since 2008-11-07 */ @Override @@ -166,7 +166,7 @@ public class Rational implements Cloneable, Comparable { /** * Multiply by another fraction. - * + * * @param val * a second rational number. * @return the product of this with the val. @@ -178,24 +178,24 @@ public class Rational implements Cloneable, Comparable { * Normalization to an coprime format will be done inside the ctor() and * is not duplicated here. */ - return (new Rational(num, deno)); + return new Rational(num, deno); } /* Rational.multiply */ /** * Multiply by a BigInteger. - * + * * @param val * a second number. * @return the product of this with the value. */ public Rational multiply(final BigInteger val) { final Rational val2 = new Rational(val, BigInteger.ONE); - return (multiply(val2)); + return multiply(val2); } /* Rational.multiply */ /** * Multiply by an integer. - * + * * @param val * a second number. * @return the product of this with the value. @@ -207,29 +207,27 @@ public class Rational implements Cloneable, Comparable { /** * Power to an integer. - * + * * @param exponent * the exponent. * @return this value raised to the power given by the exponent. If the * exponent is 0, the value 1 is returned. */ - public Rational pow(int exponent) { - if (exponent == 0) { + public Rational pow(final int exponent) { + if (exponent == 0) return new Rational(1, 1); - } final BigInteger num = a.pow(Math.abs(exponent)); final BigInteger deno = b.pow(Math.abs(exponent)); - if (exponent > 0) { - return (new Rational(num, deno)); - } else { - return (new Rational(deno, num)); - } + if (exponent > 0) + return new Rational(num, deno); + else + return new Rational(deno, num); } /* Rational.pow */ /** * Power to an integer. - * + * * @param exponent * the exponent. * @return this value raised to the power given by the exponent. If the @@ -237,14 +235,12 @@ public class Rational implements Cloneable, Comparable { * @throws Error * @since 2009-05-18 */ - public Rational pow(BigInteger exponent) throws Error { + public Rational pow(final BigInteger exponent) throws Error { /* test for overflow */ - if (exponent.compareTo(MAX_INT) == 1) { + if (exponent.compareTo(Rational.MAX_INT) == 1) throw new Error(Errors.NUMBER_TOO_LARGE); - } - if (exponent.compareTo(MIN_INT) == -1) { + if (exponent.compareTo(Rational.MIN_INT) == -1) throw new Error(Errors.NUMBER_TOO_SMALL); - } /* promote to the simpler interface above */ return pow(exponent.intValue()); @@ -252,7 +248,7 @@ public class Rational implements Cloneable, Comparable { /** * r-th root. - * + * * @param r * the inverse of the exponent. 2 for the square root, 3 for the * third root etc @@ -261,26 +257,23 @@ public class Rational implements Cloneable, Comparable { * @throws Error * @since 2009-05-18 */ - public Rational root(BigInteger r) throws Error { + public Rational root(final BigInteger r) throws Error { /* test for overflow */ - if (r.compareTo(MAX_INT) == 1) { + if (r.compareTo(Rational.MAX_INT) == 1) throw new Error(Errors.NUMBER_TOO_LARGE); - } - if (r.compareTo(MIN_INT) == -1) { + if (r.compareTo(Rational.MIN_INT) == -1) throw new Error(Errors.NUMBER_TOO_SMALL); - } final int rthroot = r.intValue(); /* cannot pull root of a negative value with even-valued root */ - if (compareTo(ZERO) == -1 && (rthroot % 2) == 0) { + if (compareTo(Rational.ZERO) == -1 && rthroot % 2 == 0) throw new Error(Errors.NEGATIVE_PARAMETER); - } /* * extract a sign such that we calculate |n|^(1/r), still r carrying any * sign */ - final boolean flipsign = (compareTo(ZERO) == -1 && (rthroot % 2) != 0) ? true : false; + final boolean flipsign = compareTo(Rational.ZERO) == -1 && rthroot % 2 != 0 ? true : false; /* * delegate the main work to ifactor#root() @@ -288,16 +281,15 @@ public class Rational implements Cloneable, Comparable { final Ifactor num = new Ifactor(a.abs()); final Ifactor deno = new Ifactor(b); final Rational resul = num.root(rthroot).divide(deno.root(rthroot)); - if (flipsign) { + if (flipsign) return resul.negate(); - } else { + else return resul; - } } /* Rational.root */ /** * Raise to a rational power. - * + * * @param exponent * The exponent. * @return This value raised to the power given by the exponent. If the @@ -305,10 +297,9 @@ public class Rational implements Cloneable, Comparable { * @throws Error * @since 2009-05-18 */ - public Rational pow(Rational exponent) throws Error { - if (exponent.a.compareTo(BigInteger.ZERO) == 0) { + public Rational pow(final Rational exponent) throws Error { + if (exponent.a.compareTo(BigInteger.ZERO) == 0) return new Rational(1, 1); - } /* * calculate (a/b)^(exponent.a/exponent.b) as @@ -320,143 +311,140 @@ public class Rational implements Cloneable, Comparable { /** * Divide by another fraction. - * + * * @param val * A second rational number. * @return The value of this/val * @throws Error */ public Rational divide(final Rational val) throws Error { - if (val.compareTo(Rational.ZERO) == 0) { + if (val.compareTo(Rational.ZERO) == 0) throw new Error(Errors.DIVISION_BY_ZERO); - } final BigInteger num = a.multiply(val.b); final BigInteger deno = b.multiply(val.a); /* * Reduction to a coprime format is done inside the ctor, and not * repeated here. */ - return (new Rational(num, deno)); + return new Rational(num, deno); } /* Rational.divide */ /** * Divide by an integer. - * + * * @param val * a second number. * @return the value of this/val * @throws Error */ - public Rational divide(BigInteger val) throws Error { - if (val.compareTo(BigInteger.ZERO) == 0) { + public Rational divide(final BigInteger val) throws Error { + if (val.compareTo(BigInteger.ZERO) == 0) throw new Error(Errors.DIVISION_BY_ZERO); - } final Rational val2 = new Rational(val, BigInteger.ONE); - return (divide(val2)); + return divide(val2); } /* Rational.divide */ /** * Divide by an integer. - * + * * @param val * A second number. * @return The value of this/val * @throws Error */ - public Rational divide(int val) throws Error { - if (val == 0) { + public Rational divide(final int val) throws Error { + if (val == 0) throw new Error(Errors.DIVISION_BY_ZERO); - } final Rational val2 = new Rational(val, 1); - return (divide(val2)); + return divide(val2); } /* Rational.divide */ /** * Add another fraction. - * + * * @param val * The number to be added * @return this+val. */ - public Rational add(Rational val) { + public Rational add(final Rational val) { final BigInteger num = a.multiply(val.b).add(b.multiply(val.a)); final BigInteger deno = b.multiply(val.b); - return (new Rational(num, deno)); + return new Rational(num, deno); } /* Rational.add */ /** * Add another integer. - * + * * @param val * The number to be added * @return this+val. */ - public Rational add(BigInteger val) { + public Rational add(final BigInteger val) { final Rational val2 = new Rational(val, BigInteger.ONE); - return (add(val2)); + return add(val2); } /* Rational.add */ /** * Add another integer. - * + * * @param val * The number to be added * @return this+val. * @since May 26 2010 */ - public Rational add(int val) { + public Rational add(final int val) { final BigInteger val2 = a.add(b.multiply(new BigInteger("" + val))); return new Rational(val2, b); } /* Rational.add */ /** * Compute the negative. - * + * * @return -this. */ public Rational negate() { - return (new Rational(a.negate(), b)); + return new Rational(a.negate(), b); } /* Rational.negate */ /** * Subtract another fraction. - * + * * @param val * the number to be subtracted from this * @return this - val. */ - public Rational subtract(Rational val) { + public Rational subtract(final Rational val) { final Rational val2 = val.negate(); - return (add(val2)); + return add(val2); } /* Rational.subtract */ /** * Subtract an integer. - * + * * @param val * the number to be subtracted from this * @return this - val. */ - public Rational subtract(BigInteger val) { + public Rational subtract(final BigInteger val) { final Rational val2 = new Rational(val, BigInteger.ONE); - return (subtract(val2)); + return subtract(val2); } /* Rational.subtract */ /** * Subtract an integer. - * + * * @param val * the number to be subtracted from this * @return this - val. */ - public Rational subtract(int val) { + public Rational subtract(final int val) { final Rational val2 = new Rational(val, 1); - return (subtract(val2)); + return subtract(val2); } /* Rational.subtract */ /** * binomial (n choose m). - * + * * @param n * the numerator. Equals the size of the set to choose from. * @param m @@ -466,20 +454,18 @@ public class Rational implements Cloneable, Comparable { * @author Richard J. Mathar * @throws Error */ - public static Rational binomial(Rational n, BigInteger m) throws Error { - if (m.compareTo(BigInteger.ZERO) == 0) { + public static Rational binomial(final Rational n, final BigInteger m) throws Error { + if (m.compareTo(BigInteger.ZERO) == 0) return Rational.ONE; - } Rational bin = n; - for (BigInteger i = new BigInteger("2"); i.compareTo(m) != 1; i = i.add(BigInteger.ONE)) { + for (BigInteger i = new BigInteger("2"); i.compareTo(m) != 1; i = i.add(BigInteger.ONE)) bin = bin.multiply(n.subtract(i.subtract(BigInteger.ONE))).divide(i); - } return bin; } /* Rational.binomial */ /** * binomial (n choose m). - * + * * @param n * the numerator. Equals the size of the set to choose from. * @param m @@ -489,20 +475,18 @@ public class Rational implements Cloneable, Comparable { * @author Richard J. Mathar * @throws Error */ - public static Rational binomial(Rational n, int m) throws Error { - if (m == 0) { + public static Rational binomial(final Rational n, final int m) throws Error { + if (m == 0) return Rational.ONE; - } Rational bin = n; - for (int i = 2; i <= m; i++) { + for (int i = 2; i <= m; i++) bin = bin.multiply(n.subtract(i - 1)).divide(i); - } return bin; } /* Rational.binomial */ /** * Hankel's symbol (n,k) - * + * * @param n * the first parameter. * @param k @@ -512,12 +496,11 @@ public class Rational implements Cloneable, Comparable { * @author Richard J. Mathar * @throws Error */ - public static Rational hankelSymb(Rational n, int k) throws Error { - if (k == 0) { + public static Rational hankelSymb(final Rational n, final int k) throws Error { + if (k == 0) return Rational.ONE; - } else if (k < 0) { + else if (k < 0) throw new Error(Errors.NEGATIVE_PARAMETER); - } Rational nkhalf = n.subtract(k).add(Rational.HALF); nkhalf = nkhalf.Pochhammer(2 * k); final Factorial f = new Factorial(); @@ -526,7 +509,7 @@ public class Rational implements Cloneable, Comparable { /** * Get the numerator. - * + * * @return The numerator of the reduced fraction. */ public BigInteger numer() { @@ -535,7 +518,7 @@ public class Rational implements Cloneable, Comparable { /** * Get the denominator. - * + * * @return The denominator of the reduced fraction. */ public BigInteger denom() { @@ -544,34 +527,33 @@ public class Rational implements Cloneable, Comparable { /** * Absolute value. - * + * * @return The absolute (non-negative) value of this. */ public Rational abs() { - return (new Rational(a.abs(), b.abs())); + return new Rational(a.abs(), b.abs()); } /** * floor(): the nearest integer not greater than this. - * + * * @return The integer rounded towards negative infinity. */ public BigInteger floor() { /* * is already integer: return the numerator */ - if (b.compareTo(BigInteger.ONE) == 0) { + if (b.compareTo(BigInteger.ONE) == 0) return a; - } else if (a.compareTo(BigInteger.ZERO) > 0) { + else if (a.compareTo(BigInteger.ZERO) > 0) return a.divide(b); - } else { + else return a.divide(b).subtract(BigInteger.ONE); - } } /* Rational.floor */ /** * ceil(): the nearest integer not smaller than this. - * + * * @return The integer rounded towards positive infinity. * @since 2010-05-26 */ @@ -579,34 +561,32 @@ public class Rational implements Cloneable, Comparable { /* * is already integer: return the numerator */ - if (b.compareTo(BigInteger.ONE) == 0) { + if (b.compareTo(BigInteger.ONE) == 0) return a; - } else if (a.compareTo(BigInteger.ZERO) > 0) { + else if (a.compareTo(BigInteger.ZERO) > 0) return a.divide(b).add(BigInteger.ONE); - } else { + else return a.divide(b); - } } /* Rational.ceil */ /** * Remove the fractional part. - * + * * @return The integer rounded towards zero. */ public BigInteger trunc() { /* * is already integer: return the numerator */ - if (b.compareTo(BigInteger.ONE) == 0) { + if (b.compareTo(BigInteger.ONE) == 0) return a; - } else { + else return a.divide(b); - } } /* Rational.trunc */ /** * Compares the value of this with another constant. - * + * * @param val * the other constant to compare with * @return -1, 0 or 1 if this number is numerically less than, equal to, or @@ -625,7 +605,7 @@ public class Rational implements Cloneable, Comparable { /** * Compares the value of this with another constant. - * + * * @param val * the other constant to compare with * @return -1, 0 or 1 if this number is numerically less than, equal to, or @@ -633,27 +613,26 @@ public class Rational implements Cloneable, Comparable { */ public int compareTo(final BigInteger val) { final Rational val2 = new Rational(val, BigInteger.ONE); - return (compareTo(val2)); + return compareTo(val2); } /* Rational.compareTo */ /** * Return a string in the format number/denom. If the denominator equals 1, * print just the numerator without a slash. - * + * * @return the human-readable version in base 10 */ @Override public String toString() { - if (b.compareTo(BigInteger.ONE) != 0) { - return (a.toString() + "/" + b.toString()); - } else { + if (b.compareTo(BigInteger.ONE) != 0) + return a.toString() + "/" + b.toString(); + else return a.toString(); - } } /* Rational.toString */ /** * Return a double value representation. - * + * * @return The value with double precision. * @since 2008-10-26 */ @@ -663,31 +642,31 @@ public class Rational implements Cloneable, Comparable { * separate invocation a.doubleValue() or b.doubleValue(), we divide * first in a BigDecimal environment and convert the result. */ - final BigDecimal adivb = (new BigDecimal(a)).divide(new BigDecimal(b), MathContext.DECIMAL128); + final BigDecimal adivb = new BigDecimal(a).divide(new BigDecimal(b), MathContext.DECIMAL128); return adivb.doubleValue(); } /* Rational.doubleValue */ /** * Return a float value representation. - * + * * @return The value with single precision. * @since 2009-08-06 */ public float floatValue() { - final BigDecimal adivb = (new BigDecimal(a)).divide(new BigDecimal(b), MathContext.DECIMAL128); + final BigDecimal adivb = new BigDecimal(a).divide(new BigDecimal(b), MathContext.DECIMAL128); return adivb.floatValue(); } /* Rational.floatValue */ /** * Return a representation as BigDecimal. - * + * * @param mc * the mathematical context which determines precision, rounding * mode etc * @return A representation as a BigDecimal floating point number. * @since 2008-10-26 */ - public BigDecimal BigDecimalValue(MathContext mc) { + public BigDecimal BigDecimalValue(final MathContext mc) { /* * numerator and denominator individually rephrased */ @@ -703,167 +682,160 @@ public class Rational implements Cloneable, Comparable { /** * Return a string in floating point format. - * + * * @param digits * The precision (number of digits) * @return The human-readable version in base 10. * @since 2008-10-25 */ - public String toFString(int digits) { + public String toFString(final int digits) { if (b.compareTo(BigInteger.ONE) != 0) { final MathContext mc = new MathContext(digits, RoundingMode.DOWN); - final BigDecimal f = (new BigDecimal(a)).divide(new BigDecimal(b), mc); - return (f.toString()); - } else { + final BigDecimal f = new BigDecimal(a).divide(new BigDecimal(b), mc); + return f.toString(); + } else return a.toString(); - } } /* Rational.toFString */ /** * Compares the value of this with another constant. - * + * * @param val * The other constant to compare with * @return The arithmetic maximum of this and val. * @since 2008-10-19 */ public Rational max(final Rational val) { - if (compareTo(val) > 0) { + if (compareTo(val) > 0) return this; - } else { + else return val; - } } /* Rational.max */ /** * Compares the value of this with another constant. - * + * * @param val * The other constant to compare with * @return The arithmetic minimum of this and val. * @since 2008-10-19 */ public Rational min(final Rational val) { - if (compareTo(val) < 0) { + if (compareTo(val) < 0) return this; - } else { + else return val; - } } /* Rational.min */ /** * Compute Pochhammer's symbol (this)_n. - * + * * @param n * The number of product terms in the evaluation. * @return Gamma(this+n)/Gamma(this) = this*(this+1)*...*(this+n-1). * @since 2008-10-25 */ public Rational Pochhammer(final BigInteger n) { - if (n.compareTo(BigInteger.ZERO) < 0) { + if (n.compareTo(BigInteger.ZERO) < 0) return null; - } else if (n.compareTo(BigInteger.ZERO) == 0) { + else if (n.compareTo(BigInteger.ZERO) == 0) return Rational.ONE; - } else { + else { /* * initialize results with the current value */ Rational res = new Rational(a, b); BigInteger i = BigInteger.ONE; - for (; i.compareTo(n) < 0; i = i.add(BigInteger.ONE)) { + for (; i.compareTo(n) < 0; i = i.add(BigInteger.ONE)) res = res.multiply(add(i)); - } return res; } } /* Rational.pochhammer */ /** * Compute pochhammer's symbol (this)_n. - * + * * @param n * The number of product terms in the evaluation. * @return Gamma(this+n)/GAMMA(this). * @since 2008-11-13 */ - public Rational Pochhammer(int n) { + public Rational Pochhammer(final int n) { return Pochhammer(new BigInteger("" + n)); } /* Rational.pochhammer */ /** * True if the value is integer. Equivalent to the indication whether a * conversion to an integer can be exact. - * + * * @since 2010-05-26 */ public boolean isBigInteger() { - return (b.abs().compareTo(BigInteger.ONE) == 0); + return b.abs().compareTo(BigInteger.ONE) == 0; } /* Rational.isBigInteger */ /** * True if the value is integer and in the range of the standard integer. * Equivalent to the indication whether a conversion to an integer can be * exact. - * + * * @since 2010-05-26 */ public boolean isInteger() { - if (!isBigInteger()) { + if (!isBigInteger()) return false; - } - return (a.compareTo(MAX_INT) <= 0 && a.compareTo(MIN_INT) >= 0); + return a.compareTo(Rational.MAX_INT) <= 0 && a.compareTo(Rational.MIN_INT) >= 0; } /* Rational.isInteger */ /** * Conversion to an integer value, if this can be done exactly. - * + * * @throws Error - * + * * @since 2011-02-13 */ int intValue() throws Error { - if (!isInteger()) { + if (!isInteger()) throw new Error(Errors.CONVERSION_ERROR); - } return a.intValue(); } /** * Conversion to a BigInteger value, if this can be done exactly. - * + * * @throws Error - * + * * @since 2012-03-02 */ BigInteger BigIntegerValue() throws Error { - if (!isBigInteger()) { + if (!isBigInteger()) throw new Error(Errors.CONVERSION_ERROR); - } return a; } /** * True if the value is a fraction of two integers in the range of the * standard integer. - * + * * @since 2010-05-26 */ public boolean isIntegerFrac() { - return (a.compareTo(MAX_INT) <= 0 && a.compareTo(MIN_INT) >= 0 && b.compareTo(MAX_INT) <= 0 && b.compareTo(MIN_INT) >= 0); + return a.compareTo(Rational.MAX_INT) <= 0 && a.compareTo(Rational.MIN_INT) >= 0 && b.compareTo(Rational.MAX_INT) <= 0 && b.compareTo(Rational.MIN_INT) >= 0; } /* Rational.isIntegerFrac */ /** * The sign: 1 if the number is >0, 0 if ==0, -1 if <0 - * + * * @return the signum of the value. * @since 2010-05-26 */ public int signum() { - return (b.signum() * a.signum()); + return b.signum() * a.signum(); } /* Rational.signum */ /** * Common lcm of the denominators of a set of rational values. - * + * * @param vals * The list/set of the rational values. * @return LCM(denom of first, denom of second, ..,denom of last) @@ -871,16 +843,15 @@ public class Rational implements Cloneable, Comparable { */ static public BigInteger lcmDenom(final Rational[] vals) { BigInteger l = BigInteger.ONE; - for (final Rational val : vals) { + for (final Rational val : vals) l = BigIntegerMath.lcm(l, val.b); - } return l; } /* Rational.lcmDenom */ /** * Normalize to coprime numerator and denominator. Also copy a negative sign * of the denominator to the numerator. - * + * * @since 2008-10-19 */ protected void normalize() { diff --git a/core/src/main/java/org/nevec/rjm/SafeMathContext.java b/core/src/main/java/org/nevec/rjm/SafeMathContext.java index 36cc24f7..95dd90e0 100644 --- a/core/src/main/java/org/nevec/rjm/SafeMathContext.java +++ b/core/src/main/java/org/nevec/rjm/SafeMathContext.java @@ -16,7 +16,7 @@ public final class SafeMathContext { return new MathContext(precision); } - public static MathContext newMathContext(int precision, RoundingMode roundingMode) { + public static MathContext newMathContext(int precision, final RoundingMode roundingMode) { if (precision <= 0) { Engine.getPlatform().getConsoleUtils().out().print(ConsoleUtils.OUTPUTLEVEL_DEBUG_MIN, "Warning! MathContext precision is <= 0 (" + precision + ")"); precision = 1; diff --git a/core/src/main/java/org/nevec/rjm/Wigner3j.java b/core/src/main/java/org/nevec/rjm/Wigner3j.java index d781195b..c4c42fa1 100644 --- a/core/src/main/java/org/nevec/rjm/Wigner3j.java +++ b/core/src/main/java/org/nevec/rjm/Wigner3j.java @@ -7,7 +7,7 @@ import it.cavallium.warppi.util.Error; /** * Exact representations of Wigner 3jm and 3nj values of half-integer arguments. - * + * * @see R. J. Mathar, Corrigendum to * "Universal factorzation fo 3n-j (j>2) symbols ..[J. Phys. A: Math. Gen.37 (2004) 3259]" * @@ -29,52 +29,50 @@ public class Wigner3j { * multplied by 2 and augmented by 1. The order of the 6 or 9 values is as * reading the corresponding standard symbol as first row, then second row * (and for the 9j symbol) third row. - * + * * @since 2011-02-15 * @author Richard J. Mathar * @throws Error */ - static public void main(String args[]) throws Error { - if (args[0].compareTo("6j") == 0) { + static public void main(final String args[]) throws Error { + if (args[0].compareTo("6j") == 0) try { final String m1 = "6"; final String t1 = "1 2 -3 -1 5 6"; final String t2 = "4 -5 3 -4 -2 -6"; String j = ""; - for (int i = 1; i <= 6; i++) { + for (int i = 1; i <= 6; i++) j += args[i] + " "; - } - final BigSurdVec w = wigner3j(m1, t1, t2, j); + final BigSurdVec w = Wigner3j.wigner3j(m1, t1, t2, j); System.out.println(w.toString()); } catch (final Exception e) { System.out.println(e.getMessage()); } - } else if (args[0].compareTo("9j") == 0) { + else if (args[0].compareTo("9j") == 0) try { final String m1 = "9"; final String t1 = "1 3 2 4 6 5 7 9 8"; final String t2 = "2 8 5 6 3 9 7 4 1"; String j = ""; - for (int i = 1; i <= 9; i++) { + for (int i = 1; i <= 9; i++) j += args[i] + " "; - } - final BigSurdVec w = wigner3j(m1, t1, t2, j); + final BigSurdVec w = Wigner3j.wigner3j(m1, t1, t2, j); System.out.println(w.toString()); } catch (final Exception e) { System.out.println(e.getMessage()); } - } else if (args[0].compareTo("3jm") == 0) { - final int j1 = (new Integer(args[1])).intValue(); - final int j2 = (new Integer(args[2])).intValue(); - final int j3 = (new Integer(args[3])).intValue(); - final int m1 = (new Integer(args[4])).intValue(); - final int m2 = (new Integer(args[5])).intValue(); - final int m3 = (new Integer(args[6])).intValue(); + else if (args[0].compareTo("3jm") == 0) { + final int j1 = new Integer(args[1]).intValue(); + final int j2 = new Integer(args[2]).intValue(); + final int j3 = new Integer(args[3]).intValue(); + final int m1 = new Integer(args[4]).intValue(); + final int m2 = new Integer(args[5]).intValue(); + final int m3 = new Integer(args[6]).intValue(); try { - BigSurd w = wigner3jm(j1, j2, j3, m1, m2, m3); + BigSurd w = Wigner3j.wigner3jm(j1, j2, j3, m1, m2, m3); System.out.println(w.toString()); w = w.multiply(new BigSurd(j3 + 1, 1)); - System.out.println("CG factor sqrt" + (j3 + 1) + "sign " + ((j2 - j2 - m3) / 2) + " " + w.toString()); + System.out.println("CG factor sqrt" + (j3 + 1) + "sign " + (j2 - j2 - m3) / 2 + " " + w.toString()); } catch (final Exception e) { System.out.println(e.getMessage()); } @@ -90,7 +88,7 @@ public class Wigner3j { * The Wigner 3jm symbol (j1,j2,j3,m1,m2,m3). All arguments of the function * are the actual parameters multiplied by 2, so they all allow an integer * representation. - * + * * @param j1 * integer representing 2*j1 * @param j2 @@ -109,20 +107,21 @@ public class Wigner3j { * @author Richard J. Mathar * @throws Error */ - static public BigSurd wigner3jm(int j1, int j2, int j3, int m1, int m2, int m3) throws Error { + static public BigSurd wigner3jm(final int j1, final int j2, final int j3, final int m1, final int m2, final int m3) + throws Error { final Rational J1 = new Rational(j1, 2); final Rational J2 = new Rational(j2, 2); final Rational J3 = new Rational(j3, 2); final Rational M1 = new Rational(m1, 2); final Rational M2 = new Rational(m2, 2); final Rational M3 = new Rational(m3, 2); - return wigner3jm(J1, J2, J3, M1, M2, M3); + return Wigner3j.wigner3jm(J1, J2, J3, M1, M2, M3); } /* wigner3jm */ /** * Wigner 3jn symbol. For the 6j symbol, the input of the 3 lines is * "1 2 3 1 5 6", "4 5 3 4 2 6" "2j1+1 2j2+1 2j3+1 2l1+1 2l2+1 2l3+1" - * + * * @param m1 * The information on the number of angular momenta. * @param t1 @@ -144,7 +143,7 @@ public class Wigner3j { * @author Richard J. Mathar * @throws Error */ - static public BigSurdVec wigner3j(String m1, String t1, String t2, String j) throws Error { + static public BigSurdVec wigner3j(final String m1, final String t1, final String t2, final String j) throws Error { /* * The first number in the line "m" is the number of angular momenta. * The rest of the line is ignored. @@ -185,16 +184,14 @@ public class Wigner3j { */ s = new Scanner(t1); int ti = 0; - while (s.hasNextInt()) { + while (s.hasNextInt()) tvec[ti++] = s.nextInt(); - } s.close(); s = new Scanner(t2); - while (s.hasNextInt()) { + while (s.hasNextInt()) tvec[ti++] = s.nextInt(); - } /* * Basic sanity checks. All indices in the first two lines address a @@ -210,9 +207,8 @@ public class Wigner3j { } final int[] jfreq = new int[m]; - for (ji = 0; ji < jfreq.length; ji++) { + for (ji = 0; ji < jfreq.length; ji++) jfreq[ji] = 0; - } /* * maintain a 0-based index which shows where the j-value has its first @@ -239,25 +235,23 @@ public class Wigner3j { * one and divide through 2. */ final Rational[] J = new Rational[jvec.length]; - for (ji = 0; ji < jvec.length; ji++) { + for (ji = 0; ji < jvec.length; ji++) J[ji] = new Rational(jvec[ji] - 1, 2); - } /* * Convert the 1-based indices to 0-based indices, loosing the sign * information. */ final int[] triadidx = new int[tvec.length]; - for (ti = 0; ti < tvec.length; ti++) { + for (ti = 0; ti < tvec.length; ti++) triadidx[ti] = Math.abs(tvec[ti]) - 1; - } /* * The M-values are all null (undetermined) at the start. */ final Rational[] M = new Rational[J.length]; s.close(); - return wigner3j(tvec, J, M, triadidx); + return Wigner3j.wigner3j(tvec, J, M, triadidx); } /* wigner3j */ /** @@ -265,7 +259,7 @@ public class Wigner3j { * triad(triadidx[0..2])*triad(triadidx[3..5])*... where each factor is a * Wigner-3jm symbol with each sign of m_i occurring once at the * corresponding l-value. - * + * * @param triadidx * 0-based indices into the list of J * @param J @@ -292,12 +286,10 @@ public class Wigner3j { */ for (int t = 0; t < triadidx.length; t += 3) { /* Ensure |J[t]-J[t+1]| <= J[t+2] <= J[t]+J[t+1] */ - if (J[triadidx[t]].subtract(J[triadidx[t + 1]]).abs().compareTo(J[triadidx[t + 2]]) > 0) { + if (J[triadidx[t]].subtract(J[triadidx[t + 1]]).abs().compareTo(J[triadidx[t + 2]]) > 0) return res; - } - if (J[triadidx[t]].add(J[triadidx[t + 1]]).compareTo(J[triadidx[t + 2]]) < 0) { + if (J[triadidx[t]].add(J[triadidx[t + 1]]).compareTo(J[triadidx[t + 2]]) < 0) return res; - } } /* @@ -308,7 +300,7 @@ public class Wigner3j { */ int freeM = -1; int freeMrank = -1; - for (int i = 0; i < triadidx.length; i++) { + for (int i = 0; i < triadidx.length; i++) /* * found an m-value which has not yet been summed over. */ @@ -339,12 +331,10 @@ public class Wigner3j { * rough work load estimator: basically (2J1+1)*(2J2+1) */ Rational wt = J[triadidx[i]].multiply(2).add(1); - if (M[triadidx[nei1]] == null) { + if (M[triadidx[nei1]] == null) wt = wt.multiply(J[triadidx[nei1]].multiply(2).add(1)); - } - if (M[triadidx[nei2]] == null) { + if (M[triadidx[nei2]] == null) wt = wt.multiply(J[triadidx[nei2]].multiply(2).add(1)); - } final int thiswt = wt.intValue(); if (freeM < 0 || thiswt < freeMrank) { freeM = i; @@ -352,19 +342,16 @@ public class Wigner3j { } } } - } - if (freeM >= 0) { + if (freeM >= 0) /* * found an m-value which has not yet been summed over. */ if (M[triadidx[freeM]] == null) { final Rational[] childM = new Rational[M.length]; - for (int ji = 0; ji < M.length; ji++) { - if (M[ji] != null) { + for (int ji = 0; ji < M.length; ji++) + if (M[ji] != null) childM[ji] = M[ji]; - } - } /* * two cases: value is fixed implicitly because already two @@ -387,7 +374,7 @@ public class Wigner3j { Rational newm = J[triadidx[freeM]].negate(); while (newm.compareTo(J[triadidx[freeM]]) <= 0) { childM[triadidx[freeM]] = tvec[freeM] > 0 ? newm : newm.negate(); - res = res.add(wigner3j(tvec, J, childM, triadidx)); + res = res.add(Wigner3j.wigner3j(tvec, J, childM, triadidx)); newm = newm.add(Rational.ONE); } } else { @@ -402,12 +389,10 @@ public class Wigner3j { * negate if these are the second occurrences of the J in * the triads */ - if (tvec[nei1] < 0) { + if (tvec[nei1] < 0) m1 = m1.negate(); - } - if (tvec[nei2] < 0) { + if (tvec[nei2] < 0) m2 = m2.negate(); - } /* m3 = -(m1+m2) */ final Rational newm = tvec[freeM] > 0 ? m1.add(m2).negate() : m1.add(m2); /* @@ -419,7 +404,7 @@ public class Wigner3j { */ if (newm.abs().compareTo(J[triadidx[freeM]]) <= 0) { childM[triadidx[freeM]] = newm; - res = res.add(wigner3j(tvec, J, childM, triadidx)); + res = res.add(Wigner3j.wigner3j(tvec, J, childM, triadidx)); } /* * zero contribution if this m-value cannot be set to any @@ -428,7 +413,6 @@ public class Wigner3j { } return res; } - } /* * reached the bottom of the loop where all M-values are assigned. Build @@ -443,47 +427,41 @@ public class Wigner3j { * negate if these are associated with in-flowing vectors in the * triads */ - if (tvec[ji] < 0) { + if (tvec[ji] < 0) m1 = m1.negate(); - } - if (tvec[ji + 1] < 0) { + if (tvec[ji + 1] < 0) m2 = m2.negate(); - } - if (tvec[ji + 2] < 0) { + if (tvec[ji + 2] < 0) m3 = m3.negate(); - } - res = res.multiply(wigner3jm(J[triadidx[ji]], J[triadidx[ji + 1]], J[triadidx[ji + 2]], m1, m2, m3)); + res = res.multiply(Wigner3j.wigner3jm(J[triadidx[ji]], J[triadidx[ji + 1]], J[triadidx[ji + 2]], m1, m2, m3)); /* * if a partial product yields zero, the total product is zero, too, * and offers an early exit. */ - if (res.signum() == 0) { + if (res.signum() == 0) return BigSurdVec.ZERO; - } } /* * The overal sign is product_{J-Mpairs} (-1)^(J-M). This is an integer * because all the J-M are integer. */ Rational sig = new Rational(); - for (int ji = 0; ji < J.length; ji++) { + for (int ji = 0; ji < J.length; ji++) sig = sig.add(J[ji]).subtract(M[ji]); - } /* * sign depends on the sum being even or odd. We assume that "sig" is * integer and look only at the numerator */ - if (sig.a.abs().testBit(0)) { + if (sig.a.abs().testBit(0)) res = res.negate(); - } return res; } /* wigner3j */ /** * The Wigner 3jm symbol (j1,j2,j3,m1,m2,m3). Warning: there is no check * that each argument is indeed half-integer. - * + * * @param j1 * integer or half-integer j1 * @param j2 @@ -502,47 +480,41 @@ public class Wigner3j { * @author Richard J. Mathar * @throws Error */ - static protected BigSurd wigner3jm(Rational j1, Rational j2, Rational j3, Rational m1, Rational m2, Rational m3) - throws Error { + static protected BigSurd wigner3jm(final Rational j1, final Rational j2, final Rational j3, final Rational m1, + final Rational m2, final Rational m3) throws Error { /* * Check that m1+m2+m3 = 0 */ - if (m1.add(m2).add(m3).signum() != 0) { + if (m1.add(m2).add(m3).signum() != 0) return BigSurd.ZERO; - } /* * Check that j1+j2+j3 is integer */ - if (j1.add(j2).add(j3).isBigInteger() == false) { + if (j1.add(j2).add(j3).isBigInteger() == false) return BigSurd.ZERO; - } /* * Check that |j1-j2|<=j3 <= |j1+j2| */ final Rational j1m2 = j1.subtract(j2); - if (j1m2.abs().compareTo(j3) > 0) { + if (j1m2.abs().compareTo(j3) > 0) return BigSurd.ZERO; - } final Rational j1p2 = j1.add(j2); - if (j1p2.abs().compareTo(j3) < 0) { + if (j1p2.abs().compareTo(j3) < 0) return BigSurd.ZERO; - } /* * Check that |m_i| <= j_i */ - if (m1.abs().compareTo(j1) > 0 || m2.abs().compareTo(j2) > 0 || m3.abs().compareTo(j3) > 0) { + if (m1.abs().compareTo(j1) > 0 || m2.abs().compareTo(j2) > 0 || m3.abs().compareTo(j3) > 0) return BigSurd.ZERO; - } /* * Check that m_i-j_i are integer. */ - if (!m1.subtract(j1).isBigInteger() || !m2.subtract(j2).isBigInteger() || !m3.subtract(j3).isBigInteger()) { + if (!m1.subtract(j1).isBigInteger() || !m2.subtract(j2).isBigInteger() || !m3.subtract(j3).isBigInteger()) return BigSurd.ZERO; - } /* * (-)^(j1-j2-m3)*delta(-m3,m1+m2)*sqrt[ (j3+j1-j2)! (j3-j1+j2)! @@ -578,27 +550,24 @@ public class Wigner3j { Rational sumk = new Rational(); while (true) { final BigInteger d = f.at(k).multiply(f.at(j1j2jk)).multiply(f.at(j1m1k)).multiply(f.at(j2m2k)).multiply(f.at(jj2m1k)).multiply(f.at(jj1m2k)); - if (k % 2 == 0) { + if (k % 2 == 0) sumk = sumk.add(new Rational(BigInteger.ONE, d)); - } else { + else sumk = sumk.subtract(new Rational(BigInteger.ONE, d)); - } j1j2jk--; j1m1k--; j2m2k--; jj2m1k++; jj1m2k++; - if (j1j2jk < 0 || j1m1k < 0 || j2m2k < 0) { + if (j1j2jk < 0 || j1m1k < 0 || j2m2k < 0) break; - } k++; } /* * sign factor (-1)^(j1-j2-m3) */ - if (j1m2.subtract(m3).intValue() % 2 != 0) { + if (j1m2.subtract(m3).intValue() % 2 != 0) sumk = sumk.negate(); - } k = j1m2.add(j3).intValue(); BigInteger s = f.at(k); diff --git a/core/src/main/java/org/nevec/rjm/Wigner3jGUI.java b/core/src/main/java/org/nevec/rjm/Wigner3jGUI.java index 60188b07..5dcdf6d6 100644 --- a/core/src/main/java/org/nevec/rjm/Wigner3jGUI.java +++ b/core/src/main/java/org/nevec/rjm/Wigner3jGUI.java @@ -24,7 +24,7 @@ import it.cavallium.warppi.util.Error; * enter any other connectivity for the triads of j-values. The actual j-values * are entered as integers (2j+1) and the computation of one value (in exact * square root representation) is started manually. - * + * * @since 2011-02-15 */ public class Wigner3jGUI implements ActionListener, ListSelectionListener { @@ -146,18 +146,16 @@ public class Wigner3jGUI implements ActionListener, ListSelectionListener { * lines that start with a hash mark. */ Scanner s = new Scanner(tr); - for (int l = 0; l < 3;) { + for (int l = 0; l < 3;) try { trias[l] = s.nextLine().trim(); - if (!trias[l].startsWith("#")) { + if (!trias[l].startsWith("#")) l++; - } } catch (final Exception e) { s.close(); outG.setText("ERROR: less than 3 lines in the triad definition"); return; } - } s.close(); @@ -196,13 +194,13 @@ public class Wigner3jGUI implements ActionListener, ListSelectionListener { /** * Interpreter parser loop. - * + * * @param e * the information on which button had been pressed in the GUI * @since 2011-02-15 */ @Override - public void actionPerformed(ActionEvent e) { + public void actionPerformed(final ActionEvent e) { final String lin = e.getActionCommand(); /* * debugging System.out.println("Ac"+e.paramString()) ; @@ -221,14 +219,14 @@ public class Wigner3jGUI implements ActionListener, ListSelectionListener { /** * Interpreter parser loop. - * + * * @param e * the information on which of the 3jn templates had been * selected in the Menu * @since 2011-02-18 */ @Override - public void valueChanged(ListSelectionEvent e) { + public void valueChanged(final ListSelectionEvent e) { switch (searJ.getMinSelectionIndex()) { case 0: inpGtria.setText("6\n"); @@ -323,11 +321,11 @@ public class Wigner3jGUI implements ActionListener, ListSelectionListener { /** * Main entry point. not taking any command line options:
* java -jar Wigner3jGUI.jar
- * + * * @since 2012-02-16 * @author Richard J. Mathar */ - public static void main(String[] args) { + public static void main(final String[] args) { final Wigner3jGUI g = new Wigner3jGUI(); g.init(); } /* main */ diff --git a/core/src/test/java/it/cavallium/warppi/AppTest.java b/core/src/test/java/it/cavallium/warppi/AppTest.java index ae73d314..d8da2569 100644 --- a/core/src/test/java/it/cavallium/warppi/AppTest.java +++ b/core/src/test/java/it/cavallium/warppi/AppTest.java @@ -1,5 +1,6 @@ package it.cavallium.warppi; +import junit.framework.Assert; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; @@ -7,32 +8,28 @@ import junit.framework.TestSuite; /** * Unit test for simple App. */ -public class AppTest - extends TestCase -{ - /** - * Create the test case - * - * @param testName name of the test case - */ - public AppTest( String testName ) - { - super( testName ); - } +public class AppTest extends TestCase { + /** + * Create the test case + * + * @param testName + * name of the test case + */ + public AppTest(final String testName) { + super(testName); + } - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( AppTest.class ); - } + /** + * @return the suite of tests being tested + */ + public static Test suite() { + return new TestSuite(AppTest.class); + } - /** - * Rigourous Test :-) - */ - public void testApp() - { - assertTrue( true ); - } + /** + * Rigourous Test :-) + */ + public void testApp() { + Assert.assertTrue(true); + } } \ No newline at end of file diff --git a/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopBoot.java b/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopBoot.java index 58f2da1a..f62dab60 100644 --- a/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopBoot.java +++ b/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopBoot.java @@ -4,7 +4,7 @@ import it.cavallium.warppi.boot.Boot; public class DesktopBoot { - public static void main(String[] args) throws Exception { + public static void main(final String[] args) throws Exception { Boot.boot(new DesktopPlatform(), args); } diff --git a/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopConsoleUtils.java b/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopConsoleUtils.java index 1377c9c3..a8d4ee9b 100644 --- a/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopConsoleUtils.java +++ b/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopConsoleUtils.java @@ -13,74 +13,74 @@ public class DesktopConsoleUtils implements it.cavallium.warppi.Platform.Console public DesktopConsoleUtils() { os = new AdvancedOutputStream() { - private void print(PrintStream stream, String str) { + private void print(final PrintStream stream, final String str) { stream.print(fixString(str)); } - private void println(PrintStream stream, String str) { + private void println(final PrintStream stream, final String str) { stream.println(fixString(str)); } - private void println(PrintStream stream) { + private void println(final PrintStream stream) { stream.println(); } - private String fixString(String str) { + private String fixString(final String str) { return str.replace("" + MathematicalSymbols.NTH_ROOT, "root").replace("" + MathematicalSymbols.SQUARE_ROOT, "sqrt").replace("" + MathematicalSymbols.POWER, "powerOf").replace("" + MathematicalSymbols.POWER_OF_TWO, "powerOfTwo").replace("" + MathematicalSymbols.SINE, "sine").replace("" + MathematicalSymbols.COSINE, "cosine").replace("" + MathematicalSymbols.TANGENT, "tangent").replace("" + MathematicalSymbols.ARC_SINE, "asin").replace("" + MathematicalSymbols.ARC_COSINE, "acos").replace("" + MathematicalSymbols.ARC_TANGENT, "atan").replace("" + MathematicalSymbols.UNDEFINED, "undefined").replace("" + MathematicalSymbols.PI, "PI").replace("" + MathematicalSymbols.EULER_NUMBER, "EULER_NUMBER").replace("" + MathematicalSymbols.X, "X").replace("" + MathematicalSymbols.Y, "Y"); } - public void println(Object str) { + @Override + public void println(final Object str) { println(0, str); } - public void println(int level) { - if (StaticVars.outputLevel >= level) { - if (StaticVars.outputLevel == 0) { + @Override + public void println(final int level) { + if (StaticVars.outputLevel >= level) + if (StaticVars.outputLevel == 0) println(System.out); - } else { + else println(System.out); - } - } } - public void println(int level, Object str) { + @Override + public void println(final int level, final Object str) { if (StaticVars.outputLevel >= level) { final String time = getTimeString(); - if (StaticVars.outputLevel == 0) { + if (StaticVars.outputLevel == 0) println(System.out, "[" + time + "] " + str); - } else { + else println(System.out, "[" + time + "] " + str); - } } } - public void print(int level, String str) { - if (StaticVars.outputLevel >= level) { - if (StaticVars.outputLevel == 0) { + @Override + public void print(final int level, final String str) { + if (StaticVars.outputLevel >= level) + if (StaticVars.outputLevel == 0) print(System.out, str); - } else { + else print(System.out, str); - } - } } - public void println(int level, String prefix, String str) { + @Override + public void println(final int level, final String prefix, final String str) { if (StaticVars.outputLevel >= level) { final String time = getTimeString(); - if (StaticVars.outputLevel == 0) { + if (StaticVars.outputLevel == 0) println(System.out, "[" + time + "][" + prefix + "] " + str); - } else { + else println(System.out, "[" + time + "][" + prefix + "] " + str); - } } } - public void println(int level, String... parts) { + @Override + public void println(final int level, final String... parts) { if (StaticVars.outputLevel >= level) { final String time = getTimeString(); - StringBuilder output = new StringBuilder(); - for (int i = 0; i < parts.length; i++) { + final StringBuilder output = new StringBuilder(); + for (int i = 0; i < parts.length; i++) if (i + 1 == parts.length) { output.append(' '); output.append(parts[i]); @@ -89,15 +89,13 @@ public class DesktopConsoleUtils implements it.cavallium.warppi.Platform.Console output.append(parts[i]); output.append(']'); } - } output.insert(0, '['); output.insert(1, time); output.insert(time.length() + 1, ']'); - if (StaticVars.outputLevel == 0) { + if (StaticVars.outputLevel == 0) println(System.out, output.toString()); - } else { + else println(System.out, output.toString()); - } } } @@ -106,7 +104,7 @@ public class DesktopConsoleUtils implements it.cavallium.warppi.Platform.Console } }; } - + @Override public AdvancedOutputStream out() { return os; diff --git a/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopGpio.java b/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopGpio.java index 9de6c896..8f35ef78 100644 --- a/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopGpio.java +++ b/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopGpio.java @@ -33,32 +33,27 @@ public class DesktopGpio implements it.cavallium.warppi.Platform.Gpio { } @Override - public void wiringPiSetupPhys() { + public void wiringPiSetupPhys() {} + + @Override + public void pinMode(final int i, final int type) { + } @Override - public void pinMode(int i, int type) { - - } + public void digitalWrite(final int pin, final int val) {} @Override - public void digitalWrite(int pin, int val) { - } + public void digitalWrite(final int pin, final boolean val) {} @Override - public void digitalWrite(int pin, boolean val) { - } + public void pwmWrite(final int pin, final int val) {} @Override - public void pwmWrite(int pin, int val) { - } + public void delayMicroseconds(final int t) {} @Override - public void delayMicroseconds(int t) { - } - - @Override - public int digitalRead(int pin) { + public int digitalRead(final int pin) { return 0; } diff --git a/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopPlatform.java b/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopPlatform.java index b36334c6..49419856 100644 --- a/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopPlatform.java +++ b/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopPlatform.java @@ -48,7 +48,7 @@ public class DesktopPlatform implements Platform { el.put("headless 8 colors engine", new JAnsi8Engine()); settings = new DesktopSettings(); } - + @Override public ConsoleUtils getConsoleUtils() { return cu; @@ -75,22 +75,22 @@ public class DesktopPlatform implements Platform { } @Override - public void setThreadName(Thread t, String name) { + public void setThreadName(final Thread t, final String name) { t.setName(name); } @Override - public void setThreadDaemon(Thread t) { + public void setThreadDaemon(final Thread t) { t.setDaemon(true); } @Override - public void setThreadDaemon(Thread t, boolean value) { + public void setThreadDaemon(final Thread t, final boolean value) { t.setDaemon(value); } @Override - public void exit(int value) { + public void exit(final int value) { System.exit(value); } @@ -110,19 +110,17 @@ public class DesktopPlatform implements Platform { } @Override - public void alphaChanged(boolean val) { + public void alphaChanged(final boolean val) { final GraphicEngine currentEngine = Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine; - if (currentEngine instanceof SwingEngine) { + if (currentEngine instanceof SwingEngine) ((SwingEngine) currentEngine).setAlphaChanged(val); - } } @Override - public void shiftChanged(boolean val) { + public void shiftChanged(final boolean val) { final GraphicEngine currentEngine = Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine; - if (currentEngine instanceof SwingEngine) { + if (currentEngine instanceof SwingEngine) ((SwingEngine) currentEngine).setShiftChanged(val); - } } @Override @@ -131,12 +129,12 @@ public class DesktopPlatform implements Platform { } @Override - public Semaphore newSemaphore(int i) { + public Semaphore newSemaphore(final int i) { return new DesktopSemaphore(i); } @Override - public URLClassLoader newURLClassLoader(URL[] urls) { + public URLClassLoader newURLClassLoader(final URL[] urls) { return new DesktopURLClassLoader(urls); } @@ -146,17 +144,17 @@ public class DesktopPlatform implements Platform { } @Override - public GraphicEngine getEngine(String string) throws NullPointerException { + public GraphicEngine getEngine(final String string) throws NullPointerException { return el.get(string); } @Override - public void throwNewExceptionInInitializerError(String text) { + public void throwNewExceptionInInitializerError(final String text) { throw new ExceptionInInitializerError(); } @Override - public String[] stacktraceToString(Error e) { + public String[] stacktraceToString(final Error e) { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); @@ -165,11 +163,11 @@ public class DesktopPlatform implements Platform { @Override public void loadPlatformRules() { - + } @Override - public void zip(String targetPath, String destinationFilePath, String password) { + public void zip(final String targetPath, final String destinationFilePath, final String password) { try { final ZipParameters parameters = new ZipParameters(); parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); @@ -185,11 +183,10 @@ public class DesktopPlatform implements Platform { final ZipFile zipFile = new ZipFile(destinationFilePath); final File targetFile = new File(targetPath); - if (targetFile.isFile()) { + if (targetFile.isFile()) zipFile.addFile(targetFile, parameters); - } else if (targetFile.isDirectory()) { + else if (targetFile.isDirectory()) zipFile.addFolder(targetFile, parameters); - } } catch (final Exception e) { e.printStackTrace(); @@ -197,12 +194,11 @@ public class DesktopPlatform implements Platform { } @Override - public void unzip(String targetZipFilePath, String destinationFolderPath, String password) { + public void unzip(final String targetZipFilePath, final String destinationFolderPath, final String password) { try { final ZipFile zipFile = new ZipFile(targetZipFilePath); - if (zipFile.isEncrypted()) { + if (zipFile.isEncrypted()) zipFile.setPassword(password); - } zipFile.extractAll(destinationFolderPath); } catch (final Exception e) { @@ -211,7 +207,7 @@ public class DesktopPlatform implements Platform { } @Override - public boolean compile(String[] command, PrintWriter printWriter, PrintWriter errors) { + public boolean compile(final String[] command, final PrintWriter printWriter, final PrintWriter errors) { return org.eclipse.jdt.internal.compiler.batch.Main.compile(command, printWriter, errors, null); } @@ -220,17 +216,15 @@ public class DesktopPlatform implements Platform { return CacheUtils.get("isRunningOnRaspberry", 24 * 60 * 60 * 1000, () -> { if (Engine.getPlatform().isJavascript()) return false; - if (Engine.getPlatform().getOsName().equals("Linux")) { + if (Engine.getPlatform().getOsName().equals("Linux")) try { final File osRelease = new File("/etc", "os-release"); return FileUtils.readLines(osRelease, "UTF-8").stream().map(String::toLowerCase).anyMatch(line -> line.contains("raspbian") && line.contains("name")); - } catch (IOException readException) { + } catch (final IOException readException) { return false; } - - } else { + else return false; - } }); } diff --git a/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopPngReader.java b/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopPngReader.java index 66e316cc..26596ca5 100644 --- a/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopPngReader.java +++ b/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopPngReader.java @@ -7,9 +7,9 @@ import it.cavallium.warppi.Platform.PngUtils.PngReader; public class DesktopPngReader implements PngReader { - private ar.com.hjg.pngj.PngReader r; - - public DesktopPngReader(InputStream resourceStream) { + private final ar.com.hjg.pngj.PngReader r; + + public DesktopPngReader(final InputStream resourceStream) { r = new ar.com.hjg.pngj.PngReader(resourceStream); } @@ -23,25 +23,24 @@ public class DesktopPngReader implements PngReader { ImageLineInt lint; while (r.hasMoreRows()) { lint = (ImageLineInt) r.readRow(); - int[] scanLine = lint.getScanline(); + final int[] scanLine = lint.getScanline(); for (int i = 0; i < width; i++) { - int offset = i * channels; + final int offset = i * channels; // Adjust the following code depending on your source image. // I need the to set the alpha channel to 0xFF000000 since my destination image // is TRANSLUCENT : BufferedImage bi = CONFIG.createCompatibleImage( width, height, Transparency.TRANSLUCENT ); // my source was 3 channels RGB without transparency int nextPixel; - if (channels == 4) { - nextPixel = (scanLine[offset] << 16) | (scanLine[offset + 1] << 8) | (scanLine[offset + 2]) | (scanLine[offset + 3] << 24); - } else if (channels == 3) { - nextPixel = (scanLine[offset] << 16) | (scanLine[offset + 1] << 8) | (scanLine[offset + 2]) | (0xFF << 24); - } else if (channels == 2) { - nextPixel = (scanLine[offset] << 16) | (scanLine[offset + 1] << 8) | 0xFF | (0xFF << 24); - } else { - nextPixel = (scanLine[offset] << 16) | (scanLine[offset] << 8) | scanLine[offset] | (0xFF << 24); - } + if (channels == 4) + nextPixel = scanLine[offset] << 16 | scanLine[offset + 1] << 8 | scanLine[offset + 2] | scanLine[offset + 3] << 24; + else if (channels == 3) + nextPixel = scanLine[offset] << 16 | scanLine[offset + 1] << 8 | scanLine[offset + 2] | 0xFF << 24; + else if (channels == 2) + nextPixel = scanLine[offset] << 16 | scanLine[offset + 1] << 8 | 0xFF | 0xFF << 24; + else + nextPixel = scanLine[offset] << 16 | scanLine[offset] << 8 | scanLine[offset] | 0xFF << 24; // I'm placing the pixels on a memory mapped file pixels[pi] = nextPixel; @@ -55,7 +54,7 @@ public class DesktopPngReader implements PngReader { @Override public int[] getSize() { - return new int[] {r.imgInfo.cols, r.imgInfo.rows}; + return new int[] { r.imgInfo.cols, r.imgInfo.rows }; } } diff --git a/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopPngUtils.java b/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopPngUtils.java index 7b3dbc75..a7ea6da4 100644 --- a/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopPngUtils.java +++ b/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopPngUtils.java @@ -7,7 +7,7 @@ import it.cavallium.warppi.Platform.PngUtils; public class DesktopPngUtils implements PngUtils { @Override - public PngReader load(InputStream resourceStream) { + public PngReader load(final InputStream resourceStream) { return new DesktopPngReader(resourceStream); } diff --git a/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopSemaphore.java b/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopSemaphore.java index 6bdceceb..6766b4b1 100644 --- a/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopSemaphore.java +++ b/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopSemaphore.java @@ -6,11 +6,11 @@ public class DesktopSemaphore extends Semaphore implements it.cavallium.warppi.P private static final long serialVersionUID = -2362314723921013871L; - public DesktopSemaphore(int arg0) { + public DesktopSemaphore(final int arg0) { super(arg0); } - public DesktopSemaphore(int permits, boolean fair) { + public DesktopSemaphore(final int permits, final boolean fair) { super(permits, fair); } } diff --git a/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopSettings.java b/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopSettings.java index 5cb200fe..a820c418 100644 --- a/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopSettings.java +++ b/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopSettings.java @@ -7,16 +7,16 @@ public class DesktopSettings implements Settings { private boolean debug; public DesktopSettings() { - this.debug = true; + debug = true; } - + @Override public boolean isDebugEnabled() { return debug; } @Override - public void setDebugEnabled(boolean debug) { + public void setDebugEnabled(final boolean debug) { this.debug = debug; } diff --git a/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopStorageUtils.java b/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopStorageUtils.java index b73cfb49..d6f3b4db 100644 --- a/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopStorageUtils.java +++ b/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopStorageUtils.java @@ -30,39 +30,41 @@ import it.cavallium.warppi.Platform.StorageUtils; import it.cavallium.warppi.util.ClassUtils; public class DesktopStorageUtils implements StorageUtils { - public boolean exists(File f) { + @Override + public boolean exists(final File f) { return f.exists(); } - public File get(String path) { + @Override + public File get(final String path) { return Paths.get(path).toFile(); } - public File get(String... path) { - if (path.length <= 1) { + @Override + public File get(final String... path) { + if (path.length <= 1) return Paths.get(path[0]).toFile(); - } else { + else return Paths.get(path[0], Arrays.copyOfRange(path, 1, path.length)).toFile(); - } } - private Map resourcesCache = new HashMap(); + private final Map resourcesCache = new HashMap<>(); + @Override @Deprecated() - public File getResource(String string) throws IOException, URISyntaxException { + public File getResource(final String string) throws IOException, URISyntaxException { final URL res = ClassUtils.classLoader.getResource(string); final boolean isResource = res != null; - if (isResource) { + if (isResource) try { final URI uri = res.toURI(); if (res.getProtocol().equalsIgnoreCase("jar")) { if (resourcesCache.containsKey(string)) { File f; - if ((f = resourcesCache.get(string)).exists()) { + if ((f = resourcesCache.get(string)).exists()) return f; - } else { + else resourcesCache.remove(string); - } } try { FileSystems.newFileSystem(uri, Collections.emptyMap()); @@ -71,7 +73,7 @@ public class DesktopStorageUtils implements StorageUtils { } final Path myFolderPath = Paths.get(uri); - InputStream is = Files.newInputStream(myFolderPath); + final InputStream is = Files.newInputStream(myFolderPath); final File tempFile = File.createTempFile("picalcresource-", ""); tempFile.deleteOnExit(); try (FileOutputStream out = new FileOutputStream(tempFile)) { @@ -80,21 +82,20 @@ public class DesktopStorageUtils implements StorageUtils { resourcesCache.put(string, tempFile); return tempFile; - } else { + } else return Paths.get(uri).toFile(); - } } catch (final java.lang.IllegalArgumentException e) { throw e; } - } else { + else return Paths.get(string.substring(1)).toFile(); - } } + @Override public InputStream getResourceStream(String string) throws IOException, URISyntaxException { final URL res = ClassUtils.classLoader.getResource(string); final boolean isResource = res != null; - if (isResource) { + if (isResource) try { final URI uri = res.toURI(); if (res.getProtocol().equalsIgnoreCase("jar")) { @@ -105,63 +106,69 @@ public class DesktopStorageUtils implements StorageUtils { } final Path myFolderPath = Paths.get(uri); return Files.newInputStream(myFolderPath); - } else { + } else return Files.newInputStream(Paths.get(uri)); - } } catch (final java.lang.IllegalArgumentException e) { throw e; } - } else { + else { if (string.length() > 0) { - char ch = string.charAt(0); - if (ch == '/' || ch == File.separatorChar) { + final char ch = string.charAt(0); + if (ch == '/' || ch == File.separatorChar) string = string.substring(1); - } } return Files.newInputStream(Paths.get(string)); } } - public List readAllLines(File file) throws IOException { + @Override + public List readAllLines(final File file) throws IOException { return Files.readAllLines(file.toPath()); } - public String read(InputStream input) throws IOException { + @Override + public String read(final InputStream input) throws IOException { try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) { return buffer.lines().collect(Collectors.joining("\n")); } } - public List walk(File dir) throws IOException { - List out = new ArrayList<>(); + @Override + public List walk(final File dir) throws IOException { + final List out = new ArrayList<>(); try (Stream paths = Files.walk(dir.toPath())) { - paths.filter(Files::isRegularFile).forEach((Path p) -> { + paths.filter(Files::isRegularFile).forEach((final Path p) -> { out.add(p.toFile()); }); } return out; } - public File relativize(File rulesPath, File f) { + @Override + public File relativize(final File rulesPath, final File f) { return rulesPath.toPath().relativize(f.toPath()).toFile(); } - public File resolve(File file, String string) { + @Override + public File resolve(final File file, final String string) { return file.toPath().resolve(string).toFile(); } - public File getParent(File f) { + @Override + public File getParent(final File f) { return f.toPath().getParent().toFile(); } - public void createDirectories(File dir) throws IOException { + @Override + public void createDirectories(final File dir) throws IOException { Files.createDirectories(dir.toPath()); } - public void write(File f, byte[] bytes, int... options) throws IOException { - StandardOpenOption[] noptions = new StandardOpenOption[options.length]; + @Override + public void write(final File f, final byte[] bytes, final int... options) throws IOException { + final StandardOpenOption[] noptions = new StandardOpenOption[options.length]; int i = 0; - for (int opt : options) { + for (final int opt : options) { switch (opt) { case StorageUtils.OpenOptionCreate: { noptions[i] = StandardOpenOption.CREATE; @@ -180,7 +187,8 @@ public class DesktopStorageUtils implements StorageUtils { Files.write(f.toPath(), bytes, noptions); } - public List readAllLines(InputStream input) throws IOException { + @Override + public List readAllLines(final InputStream input) throws IOException { try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) { return buffer.lines().collect(Collectors.toList()); } diff --git a/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopURLClassLoader.java b/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopURLClassLoader.java index c716e504..2e6af5d6 100644 --- a/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopURLClassLoader.java +++ b/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopURLClassLoader.java @@ -6,7 +6,7 @@ import it.cavallium.warppi.Platform.URLClassLoader; public class DesktopURLClassLoader extends java.net.URLClassLoader implements URLClassLoader { - public DesktopURLClassLoader(URL[] urls) { + public DesktopURLClassLoader(final URL[] urls) { super(urls); } diff --git a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi24bitcolors/JAnsi24bitEngine.java b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi24bitcolors/JAnsi24bitEngine.java index fe7d09dc..2c894b7f 100644 --- a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi24bitcolors/JAnsi24bitEngine.java +++ b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi24bitcolors/JAnsi24bitEngine.java @@ -28,9 +28,8 @@ public class JAnsi24bitEngine implements it.cavallium.warppi.gui.graphicengine.G private boolean win = false; private Key precKey = null; - public JAnsi24bitEngine() { - } - + public JAnsi24bitEngine() {} + @Override public int[] getSize() { new ConsoleHandler(); @@ -43,18 +42,18 @@ public class JAnsi24bitEngine implements it.cavallium.warppi.gui.graphicengine.G } @Override - public void setTitle(String title) { + public void setTitle(final String title) { this.title = title; } @Override - public void setResizable(boolean r) { + public void setResizable(final boolean r) { // TODO Auto-generated method stub } @Override - public void setDisplayMode(int ww, int wh) { + public void setDisplayMode(final int ww, final int wh) { // TODO Auto-generated method stub } @@ -68,11 +67,11 @@ public class JAnsi24bitEngine implements it.cavallium.warppi.gui.graphicengine.G } @Override - public void create(Runnable onInitialized) { + public void create(final Runnable onInitialized) { title = Engine.getPlatform().getSettings().getCalculatorName(); r = new JAnsi24bitRenderer(); - C_WIDTH = StaticVars.screenSize[0] / C_MUL_X; - C_HEIGHT = StaticVars.screenSize[1] / C_MUL_Y; + JAnsi24bitEngine.C_WIDTH = StaticVars.screenSize[0] / JAnsi24bitEngine.C_MUL_X; + JAnsi24bitEngine.C_HEIGHT = StaticVars.screenSize[1] / JAnsi24bitEngine.C_MUL_Y; StaticVars.outputLevel = -1; AnsiConsole.systemInstall(); if (Utils.isWindows() && !StaticVars.startupArguments.isMSDOSModeEnabled()) { @@ -133,9 +132,8 @@ public class JAnsi24bitEngine implements it.cavallium.warppi.gui.graphicengine.G break; } } - if (key != null) { + if (key != null) Keyboard.keyPressed(key); - } } }); @@ -143,9 +141,8 @@ public class JAnsi24bitEngine implements it.cavallium.warppi.gui.graphicengine.G t.start(); } stopped = false; - if (onInitialized != null) { + if (onInitialized != null) onInitialized.run(); - } } @Override @@ -169,7 +166,7 @@ public class JAnsi24bitEngine implements it.cavallium.warppi.gui.graphicengine.G } @Override - public void start(RenderingLoop d) { + public void start(final RenderingLoop d) { renderLoop = d; final Thread th = new Thread(() -> { try { @@ -184,9 +181,8 @@ public class JAnsi24bitEngine implements it.cavallium.warppi.gui.graphicengine.G if (extraTimeInt + deltaInt < 200) { Thread.sleep(200 - (extraTimeInt + deltaInt)); extratime = 0; - } else { + } else extratime += delta - 200d; - } } } catch (final InterruptedException e) { e.printStackTrace(); @@ -201,7 +197,7 @@ public class JAnsi24bitEngine implements it.cavallium.warppi.gui.graphicengine.G public void repaint() { renderLoop.refresh(); r.curColor = new int[] { 0x00, 0x87, 0x00 }; - r.glDrawStringCenter((C_WIDTH * C_MUL_X) / 2, 0, title); + r.glDrawStringCenter(JAnsi24bitEngine.C_WIDTH * JAnsi24bitEngine.C_MUL_X / 2, 0, title); if (win) { WindowsSupport.writeConsole(JAnsi24bitRenderer.ANSI_PREFIX + "0;0f"); WindowsSupport.writeConsole(JAnsi24bitRenderer.ANSI_PREFIX + "?12l"); @@ -217,15 +213,13 @@ public class JAnsi24bitEngine implements it.cavallium.warppi.gui.graphicengine.G int[] curFgColor = new int[] { -1, -1, -1 }; String out = ""; char outchar = ' '; - for (int y = 0; y < C_HEIGHT; y++) { - for (int x = 0; x < C_WIDTH; x++) { + for (int y = 0; y < JAnsi24bitEngine.C_HEIGHT; y++) + for (int x = 0; x < JAnsi24bitEngine.C_WIDTH; x++) { //BG color - int[][] pixs = new int[C_MUL_X * C_MUL_Y][]; - for (int paddY = 0; paddY < C_MUL_Y; paddY++) { - for (int paddX = 0; paddX < C_MUL_X; paddX++) { - pixs[paddX + paddY * C_MUL_X] = r.bgColorMatrixSs[(x * C_MUL_X + paddX) + (y * C_MUL_Y + paddY) * r.size[0]]; - } - } + int[][] pixs = new int[JAnsi24bitEngine.C_MUL_X * JAnsi24bitEngine.C_MUL_Y][]; + for (int paddY = 0; paddY < JAnsi24bitEngine.C_MUL_Y; paddY++) + for (int paddX = 0; paddX < JAnsi24bitEngine.C_MUL_X; paddX++) + pixs[paddX + paddY * JAnsi24bitEngine.C_MUL_X] = r.bgColorMatrixSs[x * JAnsi24bitEngine.C_MUL_X + paddX + (y * JAnsi24bitEngine.C_MUL_Y + paddY) * r.size[0]]; int[] newpix = new int[3]; for (final int[] pix : pixs) { newpix[0] += pix[0]; @@ -235,15 +229,13 @@ public class JAnsi24bitEngine implements it.cavallium.warppi.gui.graphicengine.G newpix[0] /= pixs.length; newpix[1] /= pixs.length; newpix[2] /= pixs.length; - r.bgColorMatrix[x + y * C_WIDTH] = newpix; + r.bgColorMatrix[x + y * JAnsi24bitEngine.C_WIDTH] = newpix; //FG color - pixs = new int[C_MUL_X * C_MUL_Y][]; - for (int paddY = 0; paddY < C_MUL_Y; paddY++) { - for (int paddX = 0; paddX < C_MUL_X; paddX++) { - pixs[paddX + paddY * C_MUL_X] = r.fgColorMatrixSs[(x * C_MUL_X + paddX) + (y * C_MUL_Y + paddY) * r.size[0]]; - } - } + pixs = new int[JAnsi24bitEngine.C_MUL_X * JAnsi24bitEngine.C_MUL_Y][]; + for (int paddY = 0; paddY < JAnsi24bitEngine.C_MUL_Y; paddY++) + for (int paddX = 0; paddX < JAnsi24bitEngine.C_MUL_X; paddX++) + pixs[paddX + paddY * JAnsi24bitEngine.C_MUL_X] = r.fgColorMatrixSs[x * JAnsi24bitEngine.C_MUL_X + paddX + (y * JAnsi24bitEngine.C_MUL_Y + paddY) * r.size[0]]; newpix = new int[3]; for (final int[] pix : pixs) { newpix[0] += pix[0]; @@ -253,47 +245,42 @@ public class JAnsi24bitEngine implements it.cavallium.warppi.gui.graphicengine.G newpix[0] /= pixs.length; newpix[1] /= pixs.length; newpix[2] /= pixs.length; - r.fgColorMatrix[x + y * C_WIDTH] = newpix; + r.fgColorMatrix[x + y * JAnsi24bitEngine.C_WIDTH] = newpix; } - } - for (int y = 0; y < C_HEIGHT; y++) { - for (int x = 0; x < C_WIDTH; x++) { - curBgColor = r.bgColorMatrix[x + y * C_WIDTH]; - curFgColor = r.fgColorMatrix[x + y * C_WIDTH]; + for (int y = 0; y < JAnsi24bitEngine.C_HEIGHT; y++) { + for (int x = 0; x < JAnsi24bitEngine.C_WIDTH; x++) { + curBgColor = r.bgColorMatrix[x + y * JAnsi24bitEngine.C_WIDTH]; + curFgColor = r.fgColorMatrix[x + y * JAnsi24bitEngine.C_WIDTH]; if (precBgColor != curBgColor) { out = JAnsi24bitRenderer.ANSI_PREFIX + JAnsi24bitRenderer.ansiBgColorPrefix + curBgColor[0] + ";" + curBgColor[1] + ";" + curBgColor[2] + JAnsi24bitRenderer.ansiColorSuffix; - if (win) { + if (win) WindowsSupport.writeConsole(out); - } else { + else AnsiConsole.out.print(out); - } } if (precFgColor != curFgColor) { out = JAnsi24bitRenderer.ANSI_PREFIX + JAnsi24bitRenderer.ansiFgColorPrefix + curFgColor[0] + ";" + curFgColor[1] + ";" + curFgColor[2] + JAnsi24bitRenderer.ansiColorSuffix; - if (win) { + if (win) WindowsSupport.writeConsole(out); - } else { + else AnsiConsole.out.print(out); - } } - outchar = r.charmatrix[x + y * C_WIDTH]; - if (win) { + outchar = r.charmatrix[x + y * JAnsi24bitEngine.C_WIDTH]; + if (win) WindowsSupport.writeConsole(outchar + ""); - } else { + else AnsiConsole.out.print(outchar); - } precBgColor = curBgColor; precFgColor = curFgColor; } - if (win) { + if (win) //System.out.println(ch); WindowsSupport.writeConsole("\r\n"); - } else { + else AnsiConsole.out.println(); - } } } @@ -303,26 +290,26 @@ public class JAnsi24bitEngine implements it.cavallium.warppi.gui.graphicengine.G } @Override - public JAnsi24bitFont loadFont(String file) throws IOException { + public JAnsi24bitFont loadFont(final String file) throws IOException { return new JAnsi24bitFont(); } @Override - public JAnsi24bitFont loadFont(String path, String file) throws IOException { + public JAnsi24bitFont loadFont(final String path, final String file) throws IOException { return new JAnsi24bitFont(); } @Override - public JAnsi24bitSkin loadSkin(String file) throws IOException { + public JAnsi24bitSkin loadSkin(final String file) throws IOException { return new JAnsi24bitSkin(file); } @Override public void waitForExit() { try { - do { + do Thread.sleep(500); - } while (stopped == false); + while (stopped == false); } catch (final InterruptedException e) { } @@ -330,9 +317,8 @@ public class JAnsi24bitEngine implements it.cavallium.warppi.gui.graphicengine.G @Override public boolean isSupported() { - if (StaticVars.startupArguments.isMSDOSModeEnabled() || (StaticVars.startupArguments.isEngineForced() && StaticVars.startupArguments.isHeadless24bitEngineForced() == false)) { + if (StaticVars.startupArguments.isMSDOSModeEnabled() || StaticVars.startupArguments.isEngineForced() && StaticVars.startupArguments.isHeadless24bitEngineForced() == false) return false; - } return true; } diff --git a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi24bitcolors/JAnsi24bitFont.java b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi24bitcolors/JAnsi24bitFont.java index f8b60d9b..7d25423c 100644 --- a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi24bitcolors/JAnsi24bitFont.java +++ b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi24bitcolors/JAnsi24bitFont.java @@ -8,24 +8,24 @@ import it.cavallium.warppi.gui.graphicengine.GraphicEngine; public class JAnsi24bitFont implements BinaryFont { @Override - public void load(String file) throws IOException { + public void load(final String file) throws IOException { } @Override - public void initialize(GraphicEngine d) { + public void initialize(final GraphicEngine d) { // TODO Auto-generated method stub } @Override - public void use(GraphicEngine d) { + public void use(final GraphicEngine d) { // TODO Auto-generated method stub } @Override - public int getStringWidth(String text) { + public int getStringWidth(final String text) { return 5 * text.length(); } diff --git a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi24bitcolors/JAnsi24bitRenderer.java b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi24bitcolors/JAnsi24bitRenderer.java index f26a812d..a199aa8b 100644 --- a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi24bitcolors/JAnsi24bitRenderer.java +++ b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi24bitcolors/JAnsi24bitRenderer.java @@ -12,7 +12,7 @@ public class JAnsi24bitRenderer implements Renderer { protected char[] charmatrix = new char[JAnsi24bitEngine.C_WIDTH * JAnsi24bitEngine.C_HEIGHT]; protected int[][] fgColorMatrix = new int[JAnsi24bitEngine.C_WIDTH * JAnsi24bitEngine.C_HEIGHT][3]; protected int[][] bgColorMatrix = new int[JAnsi24bitEngine.C_WIDTH * JAnsi24bitEngine.C_HEIGHT][3]; - protected int[] clearColor = rgbToIntArray(0xc5, 0xc2, 0xaf); + protected int[] clearColor = JAnsi24bitRenderer.rgbToIntArray(0xc5, 0xc2, 0xaf); protected int[] curColor = new int[] { clearColor[0], clearColor[1], clearColor[2] }; public JAnsi24bitSkin currentSkin; @@ -25,43 +25,43 @@ public class JAnsi24bitRenderer implements Renderer { public static final char FILL = 0xDB; public static final int[] TRANSPARENT = new int[] { 0, 0, 0, 1 }; - public static int[] rgbToIntArray(int r_U, int g_U, int b_U) { + public static int[] rgbToIntArray(final int r_U, final int g_U, final int b_U) { return new int[] { r_U, g_U, b_U }; } @Override - public void glColor3i(int r, int gg, int b) { - curColor = rgbToIntArray(r, gg, b); + public void glColor3i(final int r, final int gg, final int b) { + curColor = JAnsi24bitRenderer.rgbToIntArray(r, gg, b); } @Override - public void glColor(int c) { - curColor = rgbToIntArray(c >> 16 & 0xFF, c >> 8 & 0xFF, c & 0xFF); + public void glColor(final int c) { + curColor = JAnsi24bitRenderer.rgbToIntArray(c >> 16 & 0xFF, c >> 8 & 0xFF, c & 0xFF); } @Override - public void glColor4i(int red, int green, int blue, int alpha) { - curColor = rgbToIntArray(red, green, blue); + public void glColor4i(final int red, final int green, final int blue, final int alpha) { + curColor = JAnsi24bitRenderer.rgbToIntArray(red, green, blue); } @Override - public void glColor3f(float red, float green, float blue) { - curColor = rgbToIntArray((int) (red * 255), (int) (green * 255), (int) (blue * 255)); + public void glColor3f(final float red, final float green, final float blue) { + curColor = JAnsi24bitRenderer.rgbToIntArray((int) (red * 255), (int) (green * 255), (int) (blue * 255)); } @Override - public void glColor4f(float red, float green, float blue, float alpha) { - curColor = rgbToIntArray((int) (red * 255), (int) (green * 255), (int) (blue * 255)); + public void glColor4f(final float red, final float green, final float blue, final float alpha) { + curColor = JAnsi24bitRenderer.rgbToIntArray((int) (red * 255), (int) (green * 255), (int) (blue * 255)); } @Override - public void glClearColor4i(int red, int green, int blue, int alpha) { - clearColor = rgbToIntArray(red, green, blue); + public void glClearColor4i(final int red, final int green, final int blue, final int alpha) { + clearColor = JAnsi24bitRenderer.rgbToIntArray(red, green, blue); } @Override - public void glClearColor4f(float red, float green, float blue, float alpha) { - clearColor = rgbToIntArray((int) (red * 255), (int) (green * 255), (int) (blue * 255)); + public void glClearColor4f(final float red, final float green, final float blue, final float alpha) { + clearColor = JAnsi24bitRenderer.rgbToIntArray((int) (red * 255), (int) (green * 255), (int) (blue * 255)); } @Override @@ -70,36 +70,34 @@ public class JAnsi24bitRenderer implements Renderer { } @Override - public void glClearColor(int c) { - clearColor = rgbToIntArray(c >> 16 & 0xFF, c >> 8 & 0xFF, c & 0xFF); + public void glClearColor(final int c) { + clearColor = JAnsi24bitRenderer.rgbToIntArray(c >> 16 & 0xFF, c >> 8 & 0xFF, c & 0xFF); } @Override - public void glClear(int screenWidth, int screenHeight) { + public void glClear(final int screenWidth, final int screenHeight) { clearAll(); } @Override - public void glDrawLine(float x1, float y1, float x2, float y2) { + public void glDrawLine(float x1, float y1, final float x2, final float y2) { final int dx = (int) Math.abs(x2 - x1); final int dy = (int) Math.abs(y2 - y1); - final int sx = (x1 < x2) ? 1 : -1; - final int sy = (y1 < y2) ? 1 : -1; + final int sx = x1 < x2 ? 1 : -1; + final int sy = y1 < y2 ? 1 : -1; int err = dx - dy; while (true) { - if (((int) x1) >= size[0] || ((int) y1) >= size[1] || ((int) x2) >= size[0] || ((int) y2) >= size[1]) { + if ((int) x1 >= size[0] || (int) y1 >= size[1] || (int) x2 >= size[0] || (int) y2 >= size[1]) break; - } - bgColorMatrixSs[((int) x1) + ((int) y1) * size[0]] = curColor; - charmatrix[((int) x1 / JAnsi24bitEngine.C_MUL_X) + ((int) y1 / JAnsi24bitEngine.C_MUL_Y) * JAnsi24bitEngine.C_WIDTH] = ' '; + bgColorMatrixSs[(int) x1 + (int) y1 * size[0]] = curColor; + charmatrix[(int) x1 / JAnsi24bitEngine.C_MUL_X + (int) y1 / JAnsi24bitEngine.C_MUL_Y * JAnsi24bitEngine.C_WIDTH] = ' '; - if (x1 == x2 && y1 == y2) { + if (x1 == x2 && y1 == y2) break; - } final int e2 = 2 * err; @@ -116,17 +114,16 @@ public class JAnsi24bitRenderer implements Renderer { } @Override - public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth, - float uvHeight) { - if (currentSkin != null) { - glDrawSkin((int) (x), (int) (y), (int) (uvX), (int) (uvY), (int) ((uvWidth + uvX)), (int) ((uvHeight + uvY)), true); - } else { + public void glFillRect(final float x, final float y, final float width, final float height, final float uvX, + final float uvY, final float uvWidth, final float uvHeight) { + if (currentSkin != null) + glDrawSkin((int) x, (int) y, (int) uvX, (int) uvY, (int) (uvWidth + uvX), (int) (uvHeight + uvY), true); + else glFillColor(x, y, width, height); - } } @Override - public void glFillColor(float x, float y, float width, float height) { + public void glFillColor(final float x, final float y, final float width, final float height) { final int ix = (int) x; final int iy = (int) y; final int iw = (int) width; @@ -134,61 +131,54 @@ public class JAnsi24bitRenderer implements Renderer { int x1 = ix + iw; int y1 = iy + ih; - if (ix >= size[0] || iy >= size[1]) { + if (ix >= size[0] || iy >= size[1]) return; - } - if (x1 >= size[0]) { + if (x1 >= size[0]) x1 = size[0]; - } - if (y1 >= size[1]) { + if (y1 >= size[1]) y1 = size[1]; - } final int sizeW = size[0]; - for (int px = ix; px < x1; px++) { + for (int px = ix; px < x1; px++) for (int py = iy; py < y1; py++) { drawPixelAt(' ', curColor, px, py); - bgColorMatrixSs[(px) + (py) * sizeW] = curColor; - charmatrix[(px / JAnsi24bitEngine.C_MUL_X) + (py / JAnsi24bitEngine.C_MUL_Y) * sizeW / JAnsi24bitEngine.C_MUL_X] = ' '; + bgColorMatrixSs[px + py * sizeW] = curColor; + charmatrix[px / JAnsi24bitEngine.C_MUL_X + py / JAnsi24bitEngine.C_MUL_Y * sizeW / JAnsi24bitEngine.C_MUL_X] = ' '; } - } } @Override - public void glDrawCharLeft(int x, int y, char ch) { + public void glDrawCharLeft(final int x, final int y, final char ch) { final int cx = x; final int cy = y; - if (cx >= size[0] || cy >= size[1]) { + if (cx >= size[0] || cy >= size[1]) return; - } charmatrix[cx / JAnsi24bitEngine.C_MUL_X + cy / JAnsi24bitEngine.C_MUL_Y * JAnsi24bitEngine.C_WIDTH] = ch; fgColorMatrixSs[cx + cy * size[0]] = curColor; } @Override - public void glDrawCharCenter(int x, int y, char ch) { + public void glDrawCharCenter(final int x, final int y, final char ch) { glDrawCharLeft(x, y, ch); } @Override - public void glDrawCharRight(int x, int y, char ch) { + public void glDrawCharRight(final int x, final int y, final char ch) { final int cx = x - 1 * JAnsi24bitEngine.C_MUL_X; final int cy = y; - if (cx >= size[0] || cy >= size[1]) { + if (cx >= size[0] || cy >= size[1]) return; - } charmatrix[cx / JAnsi24bitEngine.C_MUL_X + cy / JAnsi24bitEngine.C_MUL_Y * JAnsi24bitEngine.C_WIDTH] = ch; fgColorMatrixSs[cx + cy * size[0]] = curColor; } @Override - public void glDrawStringLeft(float x, float y, String text) { + public void glDrawStringLeft(final float x, final float y, final String text) { final int cx = (int) x; final int cy = (int) y; int i = 0; for (final char c : text.toCharArray()) { - if (cx + i >= size[0] || cy >= size[1]) { + if (cx + i >= size[0] || cy >= size[1]) break; - } charmatrix[cx / JAnsi24bitEngine.C_MUL_X + i + cy / JAnsi24bitEngine.C_MUL_Y * JAnsi24bitEngine.C_WIDTH] = c; fgColorMatrixSs[cx + i + cy * size[0]] = curColor; i++; @@ -196,14 +186,13 @@ public class JAnsi24bitRenderer implements Renderer { } @Override - public void glDrawStringCenter(float x, float y, String text) { - final int cx = ((int) x) - (text.length() / 2) * JAnsi24bitEngine.C_MUL_X; - final int cy = ((int) y); + public void glDrawStringCenter(final float x, final float y, final String text) { + final int cx = (int) x - text.length() / 2 * JAnsi24bitEngine.C_MUL_X; + final int cy = (int) y; int i = 0; for (final char c : text.toCharArray()) { - if (cx + i >= size[0] || cy >= size[1]) { + if (cx + i >= size[0] || cy >= size[1]) break; - } charmatrix[cx / JAnsi24bitEngine.C_MUL_X + i + cy / JAnsi24bitEngine.C_MUL_Y * JAnsi24bitEngine.C_WIDTH] = c; fgColorMatrixSs[cx + i + cy * size[0]] = curColor; i++; @@ -211,12 +200,12 @@ public class JAnsi24bitRenderer implements Renderer { } @Override - public void glDrawStringRight(float x, float y, String text) { + public void glDrawStringRight(final float x, final float y, final String text) { // TODO Auto-generated method stub } - private void glDrawSkin(int x0, int y0, int s0, int t0, int s1, int t1, boolean transparent) { + private void glDrawSkin(int x0, int y0, int s0, int t0, int s1, int t1, final boolean transparent) { int[] newColor; final int onex = s0 <= s1 ? 1 : -1; final int oney = t0 <= t1 ? 1 : -1; @@ -234,55 +223,47 @@ public class JAnsi24bitRenderer implements Renderer { t1 = t00; height = t1 - t0; } - if (x0 >= size[0] || y0 >= size[1]) { + if (x0 >= size[0] || y0 >= size[1]) return; - } - if (x0 + width >= size[0]) { + if (x0 + width >= size[0]) s1 = size[0] - x0 + s0; - } - if (y0 + height >= size[1]) { + if (y0 + height >= size[1]) t1 = size[1] - y0 + t0; - } if (x0 < 0) { if (onex == -1) { width += x0; s1 += x0 + 1; - } else { + } else s0 -= x0; - } x0 = 0; } if (y0 < 0) { if (oney == -1) { height += y0; t1 += y0 + 1; - } else { + } else t0 -= y0; - } y0 = 0; } int pixelX; int pixelY; - for (int texx = 0; texx < s1 - s0; texx++) { + for (int texx = 0; texx < s1 - s0; texx++) for (int texy = 0; texy < t1 - t0; texy++) { - pixelX = (x0 + texx * onex + width); - pixelY = (y0 + texy * oney + height); - if (pixelY < size[1]) { - if (pixelX - (pixelX % size[0]) == 0) { - newColor = currentSkin.skinData[(s0 + texx) + (t0 + texy) * currentSkin.skinSize[0]]; - if (transparent) { - if (newColor.length == 3 || (newColor.length == 4 && newColor[3] != 1)) { + pixelX = x0 + texx * onex + width; + pixelY = y0 + texy * oney + height; + if (pixelY < size[1]) + if (pixelX - pixelX % size[0] == 0) { + newColor = currentSkin.skinData[s0 + texx + (t0 + texy) * currentSkin.skinSize[0]]; + if (transparent) + if (newColor.length == 3 || newColor.length == 4 && newColor[3] != 1) { charmatrix[pixelX / JAnsi24bitEngine.C_MUL_X + pixelY / JAnsi24bitEngine.C_MUL_Y * JAnsi24bitEngine.C_WIDTH] = ' '; bgColorMatrixSs[pixelX + pixelY * size[0]] = newColor; } - } } - } } - } } - private void drawPixelAt(char ch, int[] color, double x, double y) { + private void drawPixelAt(final char ch, final int[] color, final double x, final double y) { } @@ -292,9 +273,8 @@ public class JAnsi24bitRenderer implements Renderer { } protected void clearAll() { - for (int i = 0; i < JAnsi24bitEngine.C_WIDTH * JAnsi24bitEngine.C_HEIGHT; i++) { + for (int i = 0; i < JAnsi24bitEngine.C_WIDTH * JAnsi24bitEngine.C_HEIGHT; i++) charmatrix[i] = ' '; - } for (int i = 0; i < size[0] * size[1]; i++) { bgColorMatrixSs[i] = clearColor; fgColorMatrixSs[i] = new int[] { 0, 0, 0 }; diff --git a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi24bitcolors/JAnsi24bitSkin.java b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi24bitcolors/JAnsi24bitSkin.java index d5767490..55a51b20 100644 --- a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi24bitcolors/JAnsi24bitSkin.java +++ b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi24bitcolors/JAnsi24bitSkin.java @@ -13,44 +13,43 @@ public class JAnsi24bitSkin implements Skin { public int[][] skinData; public int[] skinSize; - JAnsi24bitSkin(String file) throws IOException { + JAnsi24bitSkin(final String file) throws IOException { load(file); } @Override - public void load(String file) throws IOException { + public void load(final String file) throws IOException { final BufferedImage img = ImageIO.read(this.getClass().getResource("/" + file)); - skinData = getMatrixOfImage(img); + skinData = JAnsi24bitSkin.getMatrixOfImage(img); skinSize = new int[] { img.getWidth(), img.getHeight() }; } - public static int[][] getMatrixOfImage(BufferedImage bufferedImage) { + public static int[][] getMatrixOfImage(final BufferedImage bufferedImage) { final int width = bufferedImage.getWidth(null); final int height = bufferedImage.getHeight(null); final int[][] pixels = new int[width * height][]; - for (int i = 0; i < width; i++) { + for (int i = 0; i < width; i++) for (int j = 0; j < height; j++) { final int rgb = bufferedImage.getRGB(i, j); - final int r = (rgb >> 16) & 0xFF; - final int g = (rgb >> 8) & 0xFF; + final int r = rgb >> 16 & 0xFF; + final int g = rgb >> 8 & 0xFF; final int b = rgb & 0xFF; - final boolean transparent = ((rgb >> 24) & 0xFF) <= 128; + final boolean transparent = (rgb >> 24 & 0xFF) <= 128; final int[] curCol = JAnsi24bitRenderer.rgbToIntArray(r, g, b); pixels[i + j * width] = new int[] { curCol[0], curCol[1], curCol[2], transparent ? 1 : 0 }; } - } return pixels; } @Override - public void initialize(GraphicEngine d) { + public void initialize(final GraphicEngine d) { } @Override - public void use(GraphicEngine d) { + public void use(final GraphicEngine d) { ((JAnsi24bitRenderer) d.getRenderer()).currentSkin = this; } diff --git a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi256colors/JAnsi256Engine.java b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi256colors/JAnsi256Engine.java index 4e42b4c1..2aa5d946 100644 --- a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi256colors/JAnsi256Engine.java +++ b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi256colors/JAnsi256Engine.java @@ -32,7 +32,7 @@ public class JAnsi256Engine implements it.cavallium.warppi.gui.graphicengine.Gra @Override public int[] getSize() { new ConsoleHandler(); - return new int[] { C_WIDTH, C_HEIGHT }; + return new int[] { JAnsi256Engine.C_WIDTH, JAnsi256Engine.C_HEIGHT }; } @Override @@ -41,18 +41,18 @@ public class JAnsi256Engine implements it.cavallium.warppi.gui.graphicengine.Gra } @Override - public void setTitle(String title) { + public void setTitle(final String title) { this.title = title; } @Override - public void setResizable(boolean r) { + public void setResizable(final boolean r) { // TODO Auto-generated method stub } @Override - public void setDisplayMode(int ww, int wh) { + public void setDisplayMode(final int ww, final int wh) { // TODO Auto-generated method stub } @@ -63,11 +63,11 @@ public class JAnsi256Engine implements it.cavallium.warppi.gui.graphicengine.Gra } @Override - public void create(Runnable onInitialized) { + public void create(final Runnable onInitialized) { title = Engine.getPlatform().getSettings().getCalculatorName(); r = new JAnsi256Renderer(); - C_WIDTH = StaticVars.screenSize[0] / C_MUL_X;//Main.screenSize[0]/2;//;60; - C_HEIGHT = StaticVars.screenSize[1] / C_MUL_Y;//Main.screenSize[1]/3;//;40; + JAnsi256Engine.C_WIDTH = StaticVars.screenSize[0] / JAnsi256Engine.C_MUL_X;//Main.screenSize[0]/2;//;60; + JAnsi256Engine.C_HEIGHT = StaticVars.screenSize[1] / JAnsi256Engine.C_MUL_Y;//Main.screenSize[1]/3;//;40; StaticVars.outputLevel = -1; AnsiConsole.systemInstall(); if (Utils.isWindows() && !StaticVars.startupArguments.isMSDOSModeEnabled()) { @@ -128,9 +128,8 @@ public class JAnsi256Engine implements it.cavallium.warppi.gui.graphicengine.Gra break; } } - if (key != null) { + if (key != null) Keyboard.keyPressed(key); - } } }); @@ -138,9 +137,8 @@ public class JAnsi256Engine implements it.cavallium.warppi.gui.graphicengine.Gra t.start(); } stopped = false; - if (onInitialized != null) { + if (onInitialized != null) onInitialized.run(); - } } @Override @@ -150,12 +148,12 @@ public class JAnsi256Engine implements it.cavallium.warppi.gui.graphicengine.Gra @Override public int getWidth() { - return C_WIDTH * C_MUL_X; + return JAnsi256Engine.C_WIDTH * JAnsi256Engine.C_MUL_X; } @Override public int getHeight() { - return C_HEIGHT * C_MUL_Y; + return JAnsi256Engine.C_HEIGHT * JAnsi256Engine.C_MUL_Y; } @Override @@ -164,7 +162,7 @@ public class JAnsi256Engine implements it.cavallium.warppi.gui.graphicengine.Gra } @Override - public void start(RenderingLoop d) { + public void start(final RenderingLoop d) { renderLoop = d; final Thread th = new Thread(() -> { try { @@ -179,9 +177,8 @@ public class JAnsi256Engine implements it.cavallium.warppi.gui.graphicengine.Gra if (extraTimeInt + deltaInt < 200) { Thread.sleep(200 - (extraTimeInt + deltaInt)); extratime = 0; - } else { + } else extratime += delta - 200d; - } } } catch (final InterruptedException e) { e.printStackTrace(); @@ -196,7 +193,7 @@ public class JAnsi256Engine implements it.cavallium.warppi.gui.graphicengine.Gra public void repaint() { renderLoop.refresh(); r.curColor = 0x1C; - r.glDrawStringCenter((C_WIDTH * C_MUL_X) / 2, 0, title); + r.glDrawStringCenter(JAnsi256Engine.C_WIDTH * JAnsi256Engine.C_MUL_X / 2, 0, title); if (win) { WindowsSupport.writeConsole(JAnsi24bitRenderer.ANSI_PREFIX + "0;0f"); WindowsSupport.writeConsole(JAnsi24bitRenderer.ANSI_PREFIX + "?12l"); @@ -206,47 +203,43 @@ public class JAnsi256Engine implements it.cavallium.warppi.gui.graphicengine.Gra AnsiConsole.out.print(JAnsi24bitRenderer.ANSI_PREFIX + "?12l"); AnsiConsole.out.print(JAnsi24bitRenderer.ANSI_PREFIX + "?25l"); } - for (int y = 0; y < C_HEIGHT; y++) { + for (int y = 0; y < JAnsi256Engine.C_HEIGHT; y++) { int precBgColor = -1; int precFgColor = -1; int curBgColor = -1; int curFgColor = -1; - for (int x = 0; x < C_WIDTH; x++) { - curBgColor = r.bgColorMatrix[x + y * C_WIDTH]; - curFgColor = r.fgColorMatrix[x + y * C_WIDTH]; + for (int x = 0; x < JAnsi256Engine.C_WIDTH; x++) { + curBgColor = r.bgColorMatrix[x + y * JAnsi256Engine.C_WIDTH]; + curFgColor = r.fgColorMatrix[x + y * JAnsi256Engine.C_WIDTH]; if (precBgColor != curBgColor) { final String str = JAnsi256Renderer.ANSI_PREFIX + JAnsi256Renderer.ansiBgColorPrefix + curBgColor + JAnsi256Renderer.ansiColorSuffix; - if (win) { + if (win) WindowsSupport.writeConsole(str); - } else { + else AnsiConsole.out.print(str); - } } if (precFgColor != curFgColor) { final String str = JAnsi256Renderer.ANSI_PREFIX + JAnsi256Renderer.ansiFgColorPrefix + curFgColor + JAnsi256Renderer.ansiColorSuffix; - if (win) { + if (win) WindowsSupport.writeConsole(str); - } else { + else AnsiConsole.out.print(str); - } } - final String stri = r.charmatrix[x + y * C_WIDTH] + ""; - if (win) { + final String stri = r.charmatrix[x + y * JAnsi256Engine.C_WIDTH] + ""; + if (win) WindowsSupport.writeConsole(stri); - } else { + else AnsiConsole.out.print(stri); - } precBgColor = curBgColor; precFgColor = curFgColor; } - if (win) { + if (win) WindowsSupport.writeConsole("\r\n"); - } else { + else AnsiConsole.out.println(); - } } } @@ -256,26 +249,26 @@ public class JAnsi256Engine implements it.cavallium.warppi.gui.graphicengine.Gra } @Override - public JAnsi256Font loadFont(String file) throws IOException { + public JAnsi256Font loadFont(final String file) throws IOException { return new JAnsi256Font(); } @Override - public JAnsi256Font loadFont(String path, String file) throws IOException { + public JAnsi256Font loadFont(final String path, final String file) throws IOException { return new JAnsi256Font(); } @Override - public JAnsi256Skin loadSkin(String file) throws IOException { + public JAnsi256Skin loadSkin(final String file) throws IOException { return new JAnsi256Skin(file); } @Override public void waitForExit() { try { - do { + do Thread.sleep(500); - } while (stopped == false); + while (stopped == false); } catch (final InterruptedException e) { } @@ -283,9 +276,8 @@ public class JAnsi256Engine implements it.cavallium.warppi.gui.graphicengine.Gra @Override public boolean isSupported() { - if (StaticVars.startupArguments.isMSDOSModeEnabled() || (StaticVars.startupArguments.isEngineForced() && StaticVars.startupArguments.isHeadless256EngineForced() == false)) { + if (StaticVars.startupArguments.isMSDOSModeEnabled() || StaticVars.startupArguments.isEngineForced() && StaticVars.startupArguments.isHeadless256EngineForced() == false) return false; - } return true; } diff --git a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi256colors/JAnsi256Font.java b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi256colors/JAnsi256Font.java index f3376d38..5c856928 100644 --- a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi256colors/JAnsi256Font.java +++ b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi256colors/JAnsi256Font.java @@ -8,24 +8,24 @@ import it.cavallium.warppi.gui.graphicengine.GraphicEngine; public class JAnsi256Font implements BinaryFont { @Override - public void load(String file) throws IOException { + public void load(final String file) throws IOException { } @Override - public void initialize(GraphicEngine d) { + public void initialize(final GraphicEngine d) { // TODO Auto-generated method stub } @Override - public void use(GraphicEngine d) { + public void use(final GraphicEngine d) { // TODO Auto-generated method stub } @Override - public int getStringWidth(String text) { + public int getStringWidth(final String text) { return 5 * text.length(); } diff --git a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi256colors/JAnsi256Renderer.java b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi256colors/JAnsi256Renderer.java index c2b21be5..94d377ae 100644 --- a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi256colors/JAnsi256Renderer.java +++ b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi256colors/JAnsi256Renderer.java @@ -8,7 +8,7 @@ public class JAnsi256Renderer implements Renderer { protected char[] charmatrix = new char[JAnsi256Engine.C_WIDTH * JAnsi256Engine.C_HEIGHT]; protected int[] fgColorMatrix = new int[JAnsi256Engine.C_WIDTH * JAnsi256Engine.C_HEIGHT]; protected int[] bgColorMatrix = new int[JAnsi256Engine.C_WIDTH * JAnsi256Engine.C_HEIGHT]; - protected int clearColor = rgbToX256(0xc5, 0xc2, 0xaf); + protected int clearColor = JAnsi256Renderer.rgbToX256(0xc5, 0xc2, 0xaf); protected int curColor = clearColor; public JAnsi256Skin currentSkin; @@ -21,15 +21,15 @@ public class JAnsi256Renderer implements Renderer { public static final char FILL = 0xDB; public static final int TRANSPARENT = 0xF0000; - public static int v2ci(int v_U) { + public static int v2ci(final int v_U) { return v_U < 48 ? 0 : v_U < 115 ? 1 : (v_U - 35) / 40; } - public static int colorIndex(int ir, int ig, int ib) { + public static int colorIndex(final int ir, final int ig, final int ib) { return 36 * ir + 6 * ig + ib; } - public static int distSquare(int a, int b, int c, int a_U, int b_U, int c_U) { + public static int distSquare(final int a, final int b, final int c, final int a_U, final int b_U, final int c_U) { return (a - a_U) * (a - a_U) + (b - b_U) * (b - b_U) + (c - c_U) * (c - c_U); } @@ -38,59 +38,59 @@ public class JAnsi256Renderer implements Renderer { */ public static int[] i2cv = { 0, 0x5f, 0x87, 0xaf, 0xd7, 0xff }; - public static int rgbToX256(int r_U, int g_U, int b_U) { + public static int rgbToX256(final int r_U, final int g_U, final int b_U) { // Calculate the nearest 0-based color index at 16 .. 231 - final int ir = v2ci(r_U), ig = v2ci(g_U), ib = v2ci(b_U); // 0..5 each + final int ir = JAnsi256Renderer.v2ci(r_U), ig = JAnsi256Renderer.v2ci(g_U), ib = JAnsi256Renderer.v2ci(b_U); // 0..5 each /* 0..215, lazy evaluation */ // Calculate the nearest 0-based gray index at 232 .. 255 final int average = (r_U + g_U + b_U) / 3; final int grayIndex = average > 238 ? 23 : (average - 3) / 10; // 0..23 - final int cr = i2cv[ir], cg = i2cv[ig], cb = i2cv[ib]; // r/g/b, 0..255 each + final int cr = JAnsi256Renderer.i2cv[ir], cg = JAnsi256Renderer.i2cv[ig], cb = JAnsi256Renderer.i2cv[ib]; // r/g/b, 0..255 each final int gv = 8 + 10 * grayIndex; // same value for r/g/b, 0..255 // Return the one which is nearer to the original input rgb value - final int colorErr = distSquare(cr, cg, cb, r_U, g_U, b_U); - final int grayErr = distSquare(gv, gv, gv, r_U, g_U, b_U); - return colorErr <= grayErr ? 16 + colorIndex(ir, ig, ib) : 232 + grayIndex; + final int colorErr = JAnsi256Renderer.distSquare(cr, cg, cb, r_U, g_U, b_U); + final int grayErr = JAnsi256Renderer.distSquare(gv, gv, gv, r_U, g_U, b_U); + return colorErr <= grayErr ? 16 + JAnsi256Renderer.colorIndex(ir, ig, ib) : 232 + grayIndex; } @Override - public void glColor3i(int r, int gg, int b) { - curColor = rgbToX256(r, gg, b); + public void glColor3i(final int r, final int gg, final int b) { + curColor = JAnsi256Renderer.rgbToX256(r, gg, b); } @Override - public void glColor(int c) { - curColor = rgbToX256(c >> 16 & 0xFF, c >> 8 & 0xFF, c & 0xFF); + public void glColor(final int c) { + curColor = JAnsi256Renderer.rgbToX256(c >> 16 & 0xFF, c >> 8 & 0xFF, c & 0xFF); } @Override - public void glColor4i(int red, int green, int blue, int alpha) { - curColor = rgbToX256(red, green, blue); + public void glColor4i(final int red, final int green, final int blue, final int alpha) { + curColor = JAnsi256Renderer.rgbToX256(red, green, blue); } @Override - public void glColor3f(float red, float green, float blue) { - curColor = rgbToX256((int) (red * 255), (int) (green * 255), (int) (blue * 255)); + public void glColor3f(final float red, final float green, final float blue) { + curColor = JAnsi256Renderer.rgbToX256((int) (red * 255), (int) (green * 255), (int) (blue * 255)); } @Override - public void glColor4f(float red, float green, float blue, float alpha) { - curColor = rgbToX256((int) (red * 255), (int) (green * 255), (int) (blue * 255)); + public void glColor4f(final float red, final float green, final float blue, final float alpha) { + curColor = JAnsi256Renderer.rgbToX256((int) (red * 255), (int) (green * 255), (int) (blue * 255)); } @Override - public void glClearColor4i(int red, int green, int blue, int alpha) { - clearColor = rgbToX256(red, green, blue); + public void glClearColor4i(final int red, final int green, final int blue, final int alpha) { + clearColor = JAnsi256Renderer.rgbToX256(red, green, blue); } @Override - public void glClearColor4f(float red, float green, float blue, float alpha) { - clearColor = rgbToX256((int) (red * 255), (int) (green * 255), (int) (blue * 255)); + public void glClearColor4f(final float red, final float green, final float blue, final float alpha) { + clearColor = JAnsi256Renderer.rgbToX256((int) (red * 255), (int) (green * 255), (int) (blue * 255)); } @Override @@ -99,12 +99,12 @@ public class JAnsi256Renderer implements Renderer { } @Override - public void glClearColor(int c) { - clearColor = rgbToX256(c >> 16 & 0xFF, c >> 8 & 0xFF, c & 0xFF); + public void glClearColor(final int c) { + clearColor = JAnsi256Renderer.rgbToX256(c >> 16 & 0xFF, c >> 8 & 0xFF, c & 0xFF); } @Override - public void glClear(int screenWidth, int screenHeight) { + public void glClear(final int screenWidth, final int screenHeight) { clearAll(); } @@ -118,21 +118,19 @@ public class JAnsi256Renderer implements Renderer { final int dx = (int) Math.abs(x2 - x1); final int dy = (int) Math.abs(y2 - y1); - final int sx = (x1 < x2) ? 1 : -1; - final int sy = (y1 < y2) ? 1 : -1; + final int sx = x1 < x2 ? 1 : -1; + final int sy = y1 < y2 ? 1 : -1; int err = dx - dy; while (true) { - if (((int) x1) >= JAnsi256Engine.C_WIDTH || ((int) y1) >= JAnsi256Engine.C_HEIGHT || ((int) x2) >= JAnsi256Engine.C_WIDTH || ((int) y2) >= JAnsi256Engine.C_HEIGHT) { + if ((int) x1 >= JAnsi256Engine.C_WIDTH || (int) y1 >= JAnsi256Engine.C_HEIGHT || (int) x2 >= JAnsi256Engine.C_WIDTH || (int) y2 >= JAnsi256Engine.C_HEIGHT) break; - } - bgColorMatrix[((int) x1) + ((int) y1) * JAnsi256Engine.C_WIDTH] = curColor; - charmatrix[((int) x1) + ((int) y1) * JAnsi256Engine.C_WIDTH] = ' '; + bgColorMatrix[(int) x1 + (int) y1 * JAnsi256Engine.C_WIDTH] = curColor; + charmatrix[(int) x1 + (int) y1 * JAnsi256Engine.C_WIDTH] = ' '; - if (x1 == x2 && y1 == y2) { + if (x1 == x2 && y1 == y2) break; - } final int e2 = 2 * err; @@ -149,17 +147,16 @@ public class JAnsi256Renderer implements Renderer { } @Override - public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth, - float uvHeight) { - if (currentSkin != null) { + public void glFillRect(final float x, final float y, final float width, final float height, final float uvX, + final float uvY, final float uvWidth, final float uvHeight) { + if (currentSkin != null) glDrawSkin((int) (x / JAnsi256Engine.C_MUL_X), (int) (y / JAnsi256Engine.C_MUL_Y), (int) (uvX / JAnsi256Engine.C_MUL_X), (int) (uvY / JAnsi256Engine.C_MUL_Y), (int) ((uvWidth + uvX) / JAnsi256Engine.C_MUL_X), (int) ((uvHeight + uvY) / JAnsi256Engine.C_MUL_Y), true); - } else { + else glFillColor(x, y, width, height); - } } @Override - public void glFillColor(float x, float y, float width, float height) { + public void glFillColor(final float x, final float y, final float width, final float height) { final int ix = (int) x / JAnsi256Engine.C_MUL_X; final int iy = (int) y / JAnsi256Engine.C_MUL_Y; final int iw = (int) width / JAnsi256Engine.C_MUL_X; @@ -167,60 +164,53 @@ public class JAnsi256Renderer implements Renderer { int x1 = ix + iw; int y1 = iy + ih; - if (ix >= JAnsi256Engine.C_WIDTH || iy >= JAnsi256Engine.C_WIDTH) { + if (ix >= JAnsi256Engine.C_WIDTH || iy >= JAnsi256Engine.C_WIDTH) return; - } - if (x1 >= JAnsi256Engine.C_WIDTH) { + if (x1 >= JAnsi256Engine.C_WIDTH) x1 = JAnsi256Engine.C_WIDTH; - } - if (y1 >= JAnsi256Engine.C_HEIGHT) { + if (y1 >= JAnsi256Engine.C_HEIGHT) y1 = JAnsi256Engine.C_HEIGHT; - } final int sizeW = JAnsi256Engine.C_WIDTH; - for (int px = ix; px < x1; px++) { + for (int px = ix; px < x1; px++) for (int py = iy; py < y1; py++) { - bgColorMatrix[(px) + (py) * sizeW] = curColor; - charmatrix[(px) + (py) * sizeW] = ' '; + bgColorMatrix[px + py * sizeW] = curColor; + charmatrix[px + py * sizeW] = ' '; } - } } @Override - public void glDrawCharLeft(int x, int y, char ch) { - final int cx = (x) / JAnsi256Engine.C_MUL_X; - final int cy = (y) / JAnsi256Engine.C_MUL_Y; - if (cx >= JAnsi256Engine.C_WIDTH || cy >= JAnsi256Engine.C_HEIGHT) { + public void glDrawCharLeft(final int x, final int y, final char ch) { + final int cx = x / JAnsi256Engine.C_MUL_X; + final int cy = y / JAnsi256Engine.C_MUL_Y; + if (cx >= JAnsi256Engine.C_WIDTH || cy >= JAnsi256Engine.C_HEIGHT) return; - } charmatrix[cx + cy * JAnsi256Engine.C_WIDTH] = ch; fgColorMatrix[cx + cy * JAnsi256Engine.C_WIDTH] = curColor; } @Override - public void glDrawCharCenter(int x, int y, char ch) { + public void glDrawCharCenter(final int x, final int y, final char ch) { glDrawCharLeft(x, y, ch); } @Override - public void glDrawCharRight(int x, int y, char ch) { - final int cx = (x) / JAnsi256Engine.C_MUL_X - 1; - final int cy = (y) / JAnsi256Engine.C_MUL_Y; - if (cx >= JAnsi256Engine.C_WIDTH || cy >= JAnsi256Engine.C_HEIGHT) { + public void glDrawCharRight(final int x, final int y, final char ch) { + final int cx = x / JAnsi256Engine.C_MUL_X - 1; + final int cy = y / JAnsi256Engine.C_MUL_Y; + if (cx >= JAnsi256Engine.C_WIDTH || cy >= JAnsi256Engine.C_HEIGHT) return; - } charmatrix[cx + cy * JAnsi256Engine.C_WIDTH] = ch; fgColorMatrix[cx + cy * JAnsi256Engine.C_WIDTH] = curColor; } @Override - public void glDrawStringLeft(float x, float y, String text) { - final int cx = ((int) x) / JAnsi256Engine.C_MUL_X; - final int cy = ((int) y) / JAnsi256Engine.C_MUL_Y; + public void glDrawStringLeft(final float x, final float y, final String text) { + final int cx = (int) x / JAnsi256Engine.C_MUL_X; + final int cy = (int) y / JAnsi256Engine.C_MUL_Y; int i = 0; for (final char c : text.toCharArray()) { - if (cx + i >= JAnsi256Engine.C_WIDTH || cy >= JAnsi256Engine.C_HEIGHT) { + if (cx + i >= JAnsi256Engine.C_WIDTH || cy >= JAnsi256Engine.C_HEIGHT) break; - } charmatrix[cx + i + cy * JAnsi256Engine.C_WIDTH] = c; fgColorMatrix[cx + i + cy * JAnsi256Engine.C_WIDTH] = curColor; i++; @@ -228,14 +218,13 @@ public class JAnsi256Renderer implements Renderer { } @Override - public void glDrawStringCenter(float x, float y, String text) { - final int cx = ((int) x) / JAnsi256Engine.C_MUL_X - text.length() / 2; - final int cy = ((int) y) / JAnsi256Engine.C_MUL_Y; + public void glDrawStringCenter(final float x, final float y, final String text) { + final int cx = (int) x / JAnsi256Engine.C_MUL_X - text.length() / 2; + final int cy = (int) y / JAnsi256Engine.C_MUL_Y; int i = 0; for (final char c : text.toCharArray()) { - if (cx + i >= JAnsi256Engine.C_WIDTH || cy >= JAnsi256Engine.C_HEIGHT) { + if (cx + i >= JAnsi256Engine.C_WIDTH || cy >= JAnsi256Engine.C_HEIGHT) break; - } charmatrix[cx + i + cy * JAnsi256Engine.C_WIDTH] = c; fgColorMatrix[cx + i + cy * JAnsi256Engine.C_WIDTH] = curColor; i++; @@ -243,12 +232,12 @@ public class JAnsi256Renderer implements Renderer { } @Override - public void glDrawStringRight(float x, float y, String text) { + public void glDrawStringRight(final float x, final float y, final String text) { // TODO Auto-generated method stub } - private void glDrawSkin(int x0, int y0, int s0, int t0, int s1, int t1, boolean transparent) { + private void glDrawSkin(int x0, int y0, int s0, int t0, int s1, int t1, final boolean transparent) { int newColor; final int onex = s0 <= s1 ? 1 : -1; final int oney = t0 <= t1 ? 1 : -1; @@ -266,50 +255,43 @@ public class JAnsi256Renderer implements Renderer { t1 = t00; height = t1 - t0; } - if (x0 >= JAnsi256Engine.C_WIDTH || y0 >= JAnsi256Engine.C_WIDTH) { + if (x0 >= JAnsi256Engine.C_WIDTH || y0 >= JAnsi256Engine.C_WIDTH) return; - } - if (x0 + width >= JAnsi256Engine.C_WIDTH) { + if (x0 + width >= JAnsi256Engine.C_WIDTH) s1 = JAnsi256Engine.C_WIDTH - x0 + s0; - } - if (y0 + height >= JAnsi256Engine.C_HEIGHT) { + if (y0 + height >= JAnsi256Engine.C_HEIGHT) t1 = JAnsi256Engine.C_HEIGHT - y0 + t0; - } if (x0 < 0) { if (onex == -1) { width += x0; s1 += x0 + 1; - } else { + } else s0 -= x0; - } x0 = 0; } if (y0 < 0) { if (oney == -1) { height += y0; t1 += y0 + 1; - } else { + } else t0 -= y0; - } y0 = 0; } int pixelX; int pixelY; - for (int texx = 0; texx < s1 - s0; texx++) { + for (int texx = 0; texx < s1 - s0; texx++) for (int texy = 0; texy < t1 - t0; texy++) { - pixelX = (x0 + texx * onex + width); - pixelY = (y0 + texy * oney + height); - if (pixelY < JAnsi256Engine.C_HEIGHT) { - if (pixelX - (pixelX % JAnsi256Engine.C_WIDTH) == 0) { - newColor = currentSkin.skinData[(s0 + texx) + (t0 + texy) * currentSkin.skinSize[0]]; - if (transparent && !((newColor & TRANSPARENT) == TRANSPARENT)) { + pixelX = x0 + texx * onex + width; + pixelY = y0 + texy * oney + height; + if (pixelY < JAnsi256Engine.C_HEIGHT) + if (pixelX - pixelX % JAnsi256Engine.C_WIDTH == 0) { + newColor = currentSkin.skinData[s0 + texx + (t0 + texy) * currentSkin.skinSize[0]]; + if (transparent && !((newColor & JAnsi256Renderer.TRANSPARENT) == JAnsi256Renderer.TRANSPARENT)) { charmatrix[pixelX + pixelY * JAnsi256Engine.C_WIDTH] = ' '; bgColorMatrix[pixelX + pixelY * JAnsi256Engine.C_WIDTH] = newColor; } } - } } - } } @Override diff --git a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi256colors/JAnsi256Skin.java b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi256colors/JAnsi256Skin.java index 6e44a3e0..c6c2cf78 100644 --- a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi256colors/JAnsi256Skin.java +++ b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi256colors/JAnsi256Skin.java @@ -15,48 +15,47 @@ public class JAnsi256Skin implements Skin { public int[] skinData; public int[] skinSize; - JAnsi256Skin(String file) throws IOException { + JAnsi256Skin(final String file) throws IOException { load(file); } @Override - public void load(String file) throws IOException { + public void load(final String file) throws IOException { final BufferedImage img = ImageIO.read(this.getClass().getResource("/" + file)); - skinData = getMatrixOfImage(img); + skinData = JAnsi256Skin.getMatrixOfImage(img); skinSize = new int[] { img.getWidth(), img.getHeight() }; } - public static int[] getMatrixOfImage(BufferedImage bufferedImage) { + public static int[] getMatrixOfImage(final BufferedImage bufferedImage) { BufferedImage after = new BufferedImage(bufferedImage.getWidth(null), bufferedImage.getHeight(null), BufferedImage.TYPE_INT_ARGB); final AffineTransform at = new AffineTransform(); - at.scale(1f / (JAnsi256Engine.C_MUL_X), 1f / (JAnsi256Engine.C_MUL_Y)); + at.scale(1f / JAnsi256Engine.C_MUL_X, 1f / JAnsi256Engine.C_MUL_Y); final AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR); after = scaleOp.filter(bufferedImage, after); final int width = after.getWidth(null); final int height = after.getHeight(null); final int[] pixels = new int[width * height]; - for (int i = 0; i < width; i++) { + for (int i = 0; i < width; i++) for (int j = 0; j < height; j++) { final int rgb = after.getRGB(i, j); - final int r = (rgb >> 16) & 0xFF; - final int g = (rgb >> 8) & 0xFF; + final int r = rgb >> 16 & 0xFF; + final int g = rgb >> 8 & 0xFF; final int b = rgb & 0xFF; - final boolean transparent = ((rgb >> 24) & 0xFF) <= 128; + final boolean transparent = (rgb >> 24 & 0xFF) <= 128; pixels[i + j * width] = JAnsi256Renderer.rgbToX256(r, g, b) | (transparent ? JAnsi256Renderer.TRANSPARENT : 0); } - } return pixels; } @Override - public void initialize(GraphicEngine d) { + public void initialize(final GraphicEngine d) { } @Override - public void use(GraphicEngine d) { + public void use(final GraphicEngine d) { ((JAnsi256Renderer) d.getRenderer()).currentSkin = this; } diff --git a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi8colors/JAnsi8Engine.java b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi8colors/JAnsi8Engine.java index b4e7347f..f59fd85c 100644 --- a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi8colors/JAnsi8Engine.java +++ b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi8colors/JAnsi8Engine.java @@ -32,7 +32,7 @@ public class JAnsi8Engine implements it.cavallium.warppi.gui.graphicengine.Graph @Override public int[] getSize() { new ConsoleHandler(); - return new int[] { C_WIDTH, C_HEIGHT }; + return new int[] { JAnsi8Engine.C_WIDTH, JAnsi8Engine.C_HEIGHT }; } @Override @@ -41,18 +41,18 @@ public class JAnsi8Engine implements it.cavallium.warppi.gui.graphicengine.Graph } @Override - public void setTitle(String title) { + public void setTitle(final String title) { this.title = title; } @Override - public void setResizable(boolean r) { + public void setResizable(final boolean r) { // TODO Auto-generated method stub } @Override - public void setDisplayMode(int ww, int wh) { + public void setDisplayMode(final int ww, final int wh) { // TODO Auto-generated method stub } @@ -63,11 +63,11 @@ public class JAnsi8Engine implements it.cavallium.warppi.gui.graphicengine.Graph } @Override - public void create(Runnable onInitialized) { + public void create(final Runnable onInitialized) { title = Engine.getPlatform().getSettings().getCalculatorName(); r = new JAnsi8Renderer(); - C_WIDTH = StaticVars.screenSize[0] / C_MUL_X;//Main.screenSize[0]/2;//;60; - C_HEIGHT = StaticVars.screenSize[1] / C_MUL_Y;//Main.screenSize[1]/3;//;40; + JAnsi8Engine.C_WIDTH = StaticVars.screenSize[0] / JAnsi8Engine.C_MUL_X;//Main.screenSize[0]/2;//;60; + JAnsi8Engine.C_HEIGHT = StaticVars.screenSize[1] / JAnsi8Engine.C_MUL_Y;//Main.screenSize[1]/3;//;40; StaticVars.outputLevel = -1; AnsiConsole.systemInstall(); if (Utils.isWindows() && !StaticVars.startupArguments.isMSDOSModeEnabled()) { @@ -128,9 +128,8 @@ public class JAnsi8Engine implements it.cavallium.warppi.gui.graphicengine.Graph break; } } - if (key != null) { + if (key != null) Keyboard.keyPressed(key); - } } }); @@ -138,9 +137,8 @@ public class JAnsi8Engine implements it.cavallium.warppi.gui.graphicengine.Graph t.start(); } stopped = false; - if (onInitialized != null) { + if (onInitialized != null) onInitialized.run(); - } } @Override @@ -150,12 +148,12 @@ public class JAnsi8Engine implements it.cavallium.warppi.gui.graphicengine.Graph @Override public int getWidth() { - return C_WIDTH * C_MUL_X; + return JAnsi8Engine.C_WIDTH * JAnsi8Engine.C_MUL_X; } @Override public int getHeight() { - return C_HEIGHT * C_MUL_Y; + return JAnsi8Engine.C_HEIGHT * JAnsi8Engine.C_MUL_Y; } @Override @@ -164,7 +162,7 @@ public class JAnsi8Engine implements it.cavallium.warppi.gui.graphicengine.Graph } @Override - public void start(RenderingLoop d) { + public void start(final RenderingLoop d) { renderLoop = d; final Thread th = new Thread(() -> { try { @@ -179,9 +177,8 @@ public class JAnsi8Engine implements it.cavallium.warppi.gui.graphicengine.Graph if (extraTimeInt + deltaInt < 200) { Thread.sleep(200 - (extraTimeInt + deltaInt)); extratime = 0; - } else { + } else extratime += delta - 200d; - } } } catch (final InterruptedException e) { e.printStackTrace(); @@ -196,7 +193,7 @@ public class JAnsi8Engine implements it.cavallium.warppi.gui.graphicengine.Graph public void repaint() { renderLoop.refresh(); r.curColor = 0x1C; - r.glDrawStringCenter((C_WIDTH * C_MUL_X) / 2, 0, title); + r.glDrawStringCenter(JAnsi8Engine.C_WIDTH * JAnsi8Engine.C_MUL_X / 2, 0, title); if (win) { WindowsSupport.writeConsole(JAnsi24bitRenderer.ANSI_PREFIX + "0;0f"); WindowsSupport.writeConsole(JAnsi24bitRenderer.ANSI_PREFIX + "?12l"); @@ -206,47 +203,43 @@ public class JAnsi8Engine implements it.cavallium.warppi.gui.graphicengine.Graph AnsiConsole.out.print(JAnsi24bitRenderer.ANSI_PREFIX + "?12l"); AnsiConsole.out.print(JAnsi24bitRenderer.ANSI_PREFIX + "?25l"); } - for (int y = 0; y < C_HEIGHT; y++) { + for (int y = 0; y < JAnsi8Engine.C_HEIGHT; y++) { int precBgColor = -1; int precFgColor = -1; int curBgColor = -1; int curFgColor = -1; - for (int x = 0; x < C_WIDTH; x++) { - curBgColor = (r.colorMatrix[x + y * C_WIDTH] & 0xF0) >> 4; - curFgColor = r.colorMatrix[x + y * C_WIDTH] & 0x0F; + for (int x = 0; x < JAnsi8Engine.C_WIDTH; x++) { + curBgColor = (r.colorMatrix[x + y * JAnsi8Engine.C_WIDTH] & 0xF0) >> 4; + curFgColor = r.colorMatrix[x + y * JAnsi8Engine.C_WIDTH] & 0x0F; if (precBgColor != curBgColor) { final String str = JAnsi8Renderer.ANSI_PREFIX + JAnsi8Renderer.ansiBgColorPrefix + JAnsi8Renderer.colorANSI[curBgColor] + JAnsi8Renderer.ansiColorSuffix; - if (win) { + if (win) WindowsSupport.writeConsole(str); - } else { + else AnsiConsole.out.print(str); - } } if (precFgColor != curFgColor) { final String str = JAnsi8Renderer.ANSI_PREFIX + JAnsi8Renderer.ansiFgColorPrefix + JAnsi8Renderer.colorANSI[curFgColor] + JAnsi8Renderer.ansiColorSuffix; - if (win) { + if (win) WindowsSupport.writeConsole(str); - } else { + else AnsiConsole.out.print(str); - } } - final String stri = r.charmatrix[x + y * C_WIDTH] + ""; - if (win) { + final String stri = r.charmatrix[x + y * JAnsi8Engine.C_WIDTH] + ""; + if (win) WindowsSupport.writeConsole(stri); - } else { + else AnsiConsole.out.print(stri); - } precBgColor = curBgColor; precFgColor = curFgColor; } - if (win) { + if (win) WindowsSupport.writeConsole("\r\n"); - } else { + else AnsiConsole.out.println(); - } } } @@ -256,26 +249,26 @@ public class JAnsi8Engine implements it.cavallium.warppi.gui.graphicengine.Graph } @Override - public JAnsi8Font loadFont(String file) throws IOException { + public JAnsi8Font loadFont(final String file) throws IOException { return new JAnsi8Font(); } @Override - public JAnsi8Font loadFont(String path, String file) throws IOException { + public JAnsi8Font loadFont(final String path, final String file) throws IOException { return new JAnsi8Font(); } @Override - public JAnsi8Skin loadSkin(String file) throws IOException { + public JAnsi8Skin loadSkin(final String file) throws IOException { return new JAnsi8Skin(file); } @Override public void waitForExit() { try { - do { + do Thread.sleep(500); - } while (stopped == false); + while (stopped == false); } catch (final InterruptedException e) { } @@ -283,9 +276,8 @@ public class JAnsi8Engine implements it.cavallium.warppi.gui.graphicengine.Graph @Override public boolean isSupported() { - if (StaticVars.startupArguments.isMSDOSModeEnabled() || (StaticVars.startupArguments.isEngineForced() && StaticVars.startupArguments.isHeadless8EngineForced() == false)) { + if (StaticVars.startupArguments.isMSDOSModeEnabled() || StaticVars.startupArguments.isEngineForced() && StaticVars.startupArguments.isHeadless8EngineForced() == false) return false; - } return true; } diff --git a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi8colors/JAnsi8Font.java b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi8colors/JAnsi8Font.java index a68e64eb..692648e6 100644 --- a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi8colors/JAnsi8Font.java +++ b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi8colors/JAnsi8Font.java @@ -8,24 +8,24 @@ import it.cavallium.warppi.gui.graphicengine.GraphicEngine; public class JAnsi8Font implements BinaryFont { @Override - public void load(String file) throws IOException { + public void load(final String file) throws IOException { } @Override - public void initialize(GraphicEngine d) { + public void initialize(final GraphicEngine d) { // TODO Auto-generated method stub } @Override - public void use(GraphicEngine d) { + public void use(final GraphicEngine d) { // TODO Auto-generated method stub } @Override - public int getStringWidth(String text) { + public int getStringWidth(final String text) { return 5 * text.length(); } diff --git a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi8colors/JAnsi8Renderer.java b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi8colors/JAnsi8Renderer.java index 3845b718..5fd8ffb0 100644 --- a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi8colors/JAnsi8Renderer.java +++ b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi8colors/JAnsi8Renderer.java @@ -21,7 +21,7 @@ public class JAnsi8Renderer implements Renderer { public static final String ANSI_RESET = "\u001B[0m"; public static char FILL; - private int hexColor(int red, int green, int blue) { + private int hexColor(final int red, final int green, final int blue) { final int r1 = red; int r2; final int g1 = green; @@ -31,97 +31,97 @@ public class JAnsi8Renderer implements Renderer { final float[] match = new float[16]; - // COLOR + // COLOR r2 = 0; g2 = 0; b2 = 0; match[0] = (r2 - r1) * (r2 - r1) + (g2 - g1) * (g2 - g1) + (b2 - b1) * (b2 - b1); - // COLOR + // COLOR r2 = 205; g2 = 0; b2 = 0; match[1] = (r2 - r1) * (r2 - r1) + (g2 - g1) * (g2 - g1) + (b2 - b1) * (b2 - b1); - // COLOR + // COLOR r2 = 0; g2 = 205; b2 = 0; match[2] = (r2 - r1) * (r2 - r1) + (g2 - g1) * (g2 - g1) + (b2 - b1) * (b2 - b1); - // COLOR + // COLOR r2 = 205; g2 = 205; b2 = 0; match[3] = (r2 - r1) * (r2 - r1) + (g2 - g1) * (g2 - g1) + (b2 - b1) * (b2 - b1); - // COLOR + // COLOR r2 = 0; g2 = 0; b2 = 238; match[4] = (r2 - r1) * (r2 - r1) + (g2 - g1) * (g2 - g1) + (b2 - b1) * (b2 - b1); - // COLOR + // COLOR r2 = 205; g2 = 0; b2 = 205; match[5] = (r2 - r1) * (r2 - r1) + (g2 - g1) * (g2 - g1) + (b2 - b1) * (b2 - b1); - // COLOR + // COLOR r2 = 0; g2 = 205; b2 = 205; match[6] = (r2 - r1) * (r2 - r1) + (g2 - g1) * (g2 - g1) + (b2 - b1) * (b2 - b1); - // COLOR + // COLOR r2 = 229; g2 = 229; b2 = 229; match[7] = (r2 - r1) * (r2 - r1) + (g2 - g1) * (g2 - g1) + (b2 - b1) * (b2 - b1); - // COLOR + // COLOR r2 = 127; g2 = 127; b2 = 127; match[8] = (r2 - r1) * (r2 - r1) + (g2 - g1) * (g2 - g1) + (b2 - b1) * (b2 - b1); - // COLOR + // COLOR r2 = 255; g2 = 0; b2 = 0; match[9] = (r2 - r1) * (r2 - r1) + (g2 - g1) * (g2 - g1) + (b2 - b1) * (b2 - b1); - // COLOR + // COLOR r2 = 0; g2 = 255; b2 = 0; match[0xa] = (r2 - r1) * (r2 - r1) + (g2 - g1) * (g2 - g1) + (b2 - b1) * (b2 - b1); - // COLOR + // COLOR r2 = 255; g2 = 255; b2 = 0; match[0xb] = (r2 - r1) * (r2 - r1) + (g2 - g1) * (g2 - g1) + (b2 - b1) * (b2 - b1); - // COLOR + // COLOR r2 = 92; g2 = 92; b2 = 255; match[0xc] = (r2 - r1) * (r2 - r1) + (g2 - g1) * (g2 - g1) + (b2 - b1) * (b2 - b1); - // COLOR + // COLOR r2 = 255; g2 = 0; b2 = 255; match[0xd] = (r2 - r1) * (r2 - r1) + (g2 - g1) * (g2 - g1) + (b2 - b1) * (b2 - b1); - // COLOR + // COLOR r2 = 0; g2 = 255; b2 = 255; match[0xe] = (r2 - r1) * (r2 - r1) + (g2 - g1) * (g2 - g1) + (b2 - b1) * (b2 - b1); - // COLOR + // COLOR r2 = 255; g2 = 255; b2 = 255; @@ -130,15 +130,14 @@ public class JAnsi8Renderer implements Renderer { int minIndex = 0; for (int i = 1; i < match.length; i++) { final float newnumber = match[i]; - if ((newnumber < match[minIndex])) { + if (newnumber < match[minIndex]) minIndex = i; - } } return minIndex; } - private int[] hexColorReverse(int i) { + private int[] hexColorReverse(final int i) { switch (i) { case 0x0: return new int[] { 0, 0, 0 }; @@ -175,42 +174,42 @@ public class JAnsi8Renderer implements Renderer { } } - private int colorUnion(int[] col) { + private int colorUnion(final int[] col) { return 0xFF << 24 | col[0] << 16 | col[1] << 8 | col[2]; } @Override - public void glColor3i(int r, int gg, int b) { + public void glColor3i(final int r, final int gg, final int b) { curColor = hexColor(r, gg, b); } @Override - public void glColor(int c) { + public void glColor(final int c) { curColor = hexColor(c >> 16 & 0xFF, c >> 8 & 0xFF, c & 0xFF); } @Override - public void glColor4i(int red, int green, int blue, int alpha) { + public void glColor4i(final int red, final int green, final int blue, final int alpha) { curColor = hexColor(red, green, blue); } @Override - public void glColor3f(float red, float green, float blue) { + public void glColor3f(final float red, final float green, final float blue) { curColor = hexColor((int) (red * 255), (int) (green * 255), (int) (blue * 255)); } @Override - public void glColor4f(float red, float green, float blue, float alpha) { + public void glColor4f(final float red, final float green, final float blue, final float alpha) { curColor = hexColor((int) (red * 255), (int) (green * 255), (int) (blue * 255)); } @Override - public void glClearColor4i(int red, int green, int blue, int alpha) { + public void glClearColor4i(final int red, final int green, final int blue, final int alpha) { clearColor = hexColor(red, green, blue); } @Override - public void glClearColor4f(float red, float green, float blue, float alpha) { + public void glClearColor4f(final float red, final float green, final float blue, final float alpha) { clearColor = hexColor((int) (red * 255), (int) (green * 255), (int) (blue * 255)); } @@ -220,12 +219,12 @@ public class JAnsi8Renderer implements Renderer { } @Override - public void glClearColor(int c) { + public void glClearColor(final int c) { clearColor = hexColor(c >> 16 & 0xFF, c >> 8 & 0xFF, c & 0xFF); } @Override - public void glClear(int screenWidth, int screenHeight) { + public void glClear(final int screenWidth, final int screenHeight) { clearAll(); } @@ -239,23 +238,22 @@ public class JAnsi8Renderer implements Renderer { final int dx = (int) Math.abs(x2 - x1); final int dy = (int) Math.abs(y2 - y1); - final int sx = (x1 < x2) ? 1 : -1; - final int sy = (y1 < y2) ? 1 : -1; + final int sx = x1 < x2 ? 1 : -1; + final int sy = y1 < y2 ? 1 : -1; int err = dx - dy; while (true) { - if (((int) x1) >= JAnsi8Engine.C_WIDTH || ((int) y1) >= JAnsi8Engine.C_HEIGHT || ((int) x2) >= JAnsi8Engine.C_WIDTH || ((int) y2) >= JAnsi8Engine.C_HEIGHT) { + if ((int) x1 >= JAnsi8Engine.C_WIDTH || (int) y1 >= JAnsi8Engine.C_HEIGHT || (int) x2 >= JAnsi8Engine.C_WIDTH || (int) y2 >= JAnsi8Engine.C_HEIGHT) break; - } - final int precBG = colorMatrix[((int) x1) + ((int) y1) * JAnsi8Engine.C_WIDTH] & 0xF0; - colorMatrix[((int) x1) + ((int) y1) * JAnsi8Engine.C_WIDTH] = precBG | curColor; - if (FILL == 0) initFill(); - charmatrix[((int) x1) + ((int) y1) * JAnsi8Engine.C_WIDTH] = FILL; + final int precBG = colorMatrix[(int) x1 + (int) y1 * JAnsi8Engine.C_WIDTH] & 0xF0; + colorMatrix[(int) x1 + (int) y1 * JAnsi8Engine.C_WIDTH] = precBG | curColor; + if (JAnsi8Renderer.FILL == 0) + initFill(); + charmatrix[(int) x1 + (int) y1 * JAnsi8Engine.C_WIDTH] = JAnsi8Renderer.FILL; - if (x1 == x2 && y1 == y2) { + if (x1 == x2 && y1 == y2) break; - } final int e2 = 2 * err; @@ -272,26 +270,27 @@ public class JAnsi8Renderer implements Renderer { } private void initFill() { - FILL = StaticVars.startupArguments.isMSDOSModeEnabled() ? 0xDB : '█'; + JAnsi8Renderer.FILL = StaticVars.startupArguments.isMSDOSModeEnabled() ? 0xDB : '█'; } @Override - public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth, - float uvHeight) { - if (currentSkin != null) { + public void glFillRect(final float x, final float y, final float width, final float height, final float uvX, + final float uvY, final float uvWidth, final float uvHeight) { + if (currentSkin != null) glDrawSkin((int) (x / JAnsi8Engine.C_MUL_X), (int) (y / JAnsi8Engine.C_MUL_Y), (int) (uvX / JAnsi8Engine.C_MUL_X), (int) (uvY / JAnsi8Engine.C_MUL_Y), (int) ((uvWidth + uvX) / JAnsi8Engine.C_MUL_X), (int) ((uvHeight + uvY) / JAnsi8Engine.C_MUL_Y), true); - } else { + else glFillColor(x, y, width, height); - } } @Override - public void glFillColor(float x, float y, float width, float height) { - if (FILL == 0) initFill(); - glFillColor(x, y, width, height, FILL, curColor); + public void glFillColor(final float x, final float y, final float width, final float height) { + if (JAnsi8Renderer.FILL == 0) + initFill(); + glFillColor(x, y, width, height, JAnsi8Renderer.FILL, curColor); } - private void glFillColor(float x, float y, float width, float height, char character, int color) { + private void glFillColor(final float x, final float y, final float width, final float height, final char character, + final int color) { final int ix = (int) x / JAnsi8Engine.C_MUL_X; final int iy = (int) y / JAnsi8Engine.C_MUL_Y; final int iw = (int) width / JAnsi8Engine.C_MUL_X; @@ -299,63 +298,56 @@ public class JAnsi8Renderer implements Renderer { int x1 = ix + iw; int y1 = iy + ih; - if (ix >= JAnsi8Engine.C_WIDTH || iy >= JAnsi8Engine.C_WIDTH) { + if (ix >= JAnsi8Engine.C_WIDTH || iy >= JAnsi8Engine.C_WIDTH) return; - } - if (x1 >= JAnsi8Engine.C_WIDTH) { + if (x1 >= JAnsi8Engine.C_WIDTH) x1 = JAnsi8Engine.C_WIDTH; - } - if (y1 >= JAnsi8Engine.C_HEIGHT) { + if (y1 >= JAnsi8Engine.C_HEIGHT) y1 = JAnsi8Engine.C_HEIGHT; - } final int sizeW = JAnsi8Engine.C_WIDTH; - for (int px = ix; px < x1; px++) { + for (int px = ix; px < x1; px++) for (int py = iy; py < y1; py++) { - final int precBG = colorMatrix[(px) + (py) * sizeW] & 0xF0; - colorMatrix[(px) + (py) * sizeW] = precBG | color; - charmatrix[(px) + (py) * sizeW] = character; + final int precBG = colorMatrix[px + py * sizeW] & 0xF0; + colorMatrix[px + py * sizeW] = precBG | color; + charmatrix[px + py * sizeW] = character; } - } } @Override - public void glDrawCharLeft(int x, int y, char ch) { - final int cx = (x) / JAnsi8Engine.C_MUL_X; - final int cy = (y) / JAnsi8Engine.C_MUL_Y; - if (cx >= JAnsi8Engine.C_WIDTH || cy >= JAnsi8Engine.C_HEIGHT) { + public void glDrawCharLeft(final int x, final int y, final char ch) { + final int cx = x / JAnsi8Engine.C_MUL_X; + final int cy = y / JAnsi8Engine.C_MUL_Y; + if (cx >= JAnsi8Engine.C_WIDTH || cy >= JAnsi8Engine.C_HEIGHT) return; - } charmatrix[cx + cy * JAnsi8Engine.C_WIDTH] = ch; final int precBG = colorMatrix[cx + cy * JAnsi8Engine.C_WIDTH] & 0xF0; colorMatrix[cx + cy * JAnsi8Engine.C_WIDTH] = precBG | curColor; } @Override - public void glDrawCharCenter(int x, int y, char ch) { + public void glDrawCharCenter(final int x, final int y, final char ch) { glDrawCharLeft(x, y, ch); } @Override - public void glDrawCharRight(int x, int y, char ch) { - final int cx = (x) / JAnsi8Engine.C_MUL_X - 1; - final int cy = (y) / JAnsi8Engine.C_MUL_Y; - if (cx >= JAnsi8Engine.C_WIDTH || cy >= JAnsi8Engine.C_HEIGHT) { + public void glDrawCharRight(final int x, final int y, final char ch) { + final int cx = x / JAnsi8Engine.C_MUL_X - 1; + final int cy = y / JAnsi8Engine.C_MUL_Y; + if (cx >= JAnsi8Engine.C_WIDTH || cy >= JAnsi8Engine.C_HEIGHT) return; - } charmatrix[cx + cy * JAnsi8Engine.C_WIDTH] = ch; final int precBG = colorMatrix[cx + cy * JAnsi8Engine.C_WIDTH] & 0xF0; colorMatrix[cx + cy * JAnsi8Engine.C_WIDTH] = precBG | curColor; } @Override - public void glDrawStringLeft(float x, float y, String text) { - final int cx = ((int) x) / JAnsi8Engine.C_MUL_X; - final int cy = ((int) y) / JAnsi8Engine.C_MUL_Y; + public void glDrawStringLeft(final float x, final float y, final String text) { + final int cx = (int) x / JAnsi8Engine.C_MUL_X; + final int cy = (int) y / JAnsi8Engine.C_MUL_Y; int i = 0; for (final char c : text.toCharArray()) { - if (cx + i >= JAnsi8Engine.C_WIDTH || cy >= JAnsi8Engine.C_HEIGHT) { + if (cx + i >= JAnsi8Engine.C_WIDTH || cy >= JAnsi8Engine.C_HEIGHT) break; - } charmatrix[cx + i + cy * JAnsi8Engine.C_WIDTH] = c; final int precBG = colorMatrix[cx + i + cy * JAnsi8Engine.C_WIDTH] & 0xF0; colorMatrix[cx + i + cy * JAnsi8Engine.C_WIDTH] = precBG | curColor; @@ -364,14 +356,13 @@ public class JAnsi8Renderer implements Renderer { } @Override - public void glDrawStringCenter(float x, float y, String text) { - final int cx = ((int) x) / JAnsi8Engine.C_MUL_X - text.length() / 2; - final int cy = ((int) y) / JAnsi8Engine.C_MUL_Y; + public void glDrawStringCenter(final float x, final float y, final String text) { + final int cx = (int) x / JAnsi8Engine.C_MUL_X - text.length() / 2; + final int cy = (int) y / JAnsi8Engine.C_MUL_Y; int i = 0; for (final char c : text.toCharArray()) { - if (cx + i >= JAnsi8Engine.C_WIDTH || cy >= JAnsi8Engine.C_HEIGHT) { + if (cx + i >= JAnsi8Engine.C_WIDTH || cy >= JAnsi8Engine.C_HEIGHT) break; - } charmatrix[cx + i + cy * JAnsi8Engine.C_WIDTH] = c; final int precBG = colorMatrix[cx + i + cy * JAnsi8Engine.C_WIDTH] & 0xF0; colorMatrix[cx + i + cy * JAnsi8Engine.C_WIDTH] = precBG | curColor; @@ -380,12 +371,12 @@ public class JAnsi8Renderer implements Renderer { } @Override - public void glDrawStringRight(float x, float y, String text) { + public void glDrawStringRight(final float x, final float y, final String text) { // TODO Auto-generated method stub } - private void glDrawSkin(int x0, int y0, int s0, int t0, int s1, int t1, boolean transparent) { + private void glDrawSkin(int x0, int y0, int s0, int t0, int s1, int t1, final boolean transparent) { int oldColor; int newColor; final int onex = s0 <= s1 ? 1 : -1; @@ -404,42 +395,37 @@ public class JAnsi8Renderer implements Renderer { t1 = t00; height = t1 - t0; } - if (x0 >= JAnsi8Engine.C_WIDTH || y0 >= JAnsi8Engine.C_WIDTH) { + if (x0 >= JAnsi8Engine.C_WIDTH || y0 >= JAnsi8Engine.C_WIDTH) return; - } - if (x0 + width >= JAnsi8Engine.C_WIDTH) { + if (x0 + width >= JAnsi8Engine.C_WIDTH) s1 = JAnsi8Engine.C_WIDTH - x0 + s0; - } - if (y0 + height >= JAnsi8Engine.C_HEIGHT) { + if (y0 + height >= JAnsi8Engine.C_HEIGHT) t1 = JAnsi8Engine.C_HEIGHT - y0 + t0; - } if (x0 < 0) { if (onex == -1) { width += x0; s1 += x0 + 1; - } else { + } else s0 -= x0; - } x0 = 0; } if (y0 < 0) { if (oney == -1) { height += y0; t1 += y0 + 1; - } else { + } else t0 -= y0; - } y0 = 0; } int pixelX; int pixelY; - for (int texx = 0; texx < s1 - s0; texx++) { + for (int texx = 0; texx < s1 - s0; texx++) for (int texy = 0; texy < t1 - t0; texy++) { - pixelX = (x0 + texx * onex + width); - pixelY = (y0 + texy * oney + height); - if (pixelY < JAnsi8Engine.C_HEIGHT) { - if (pixelX - (pixelX % JAnsi8Engine.C_WIDTH) == 0) { - newColor = currentSkin.skinData[(s0 + texx) + (t0 + texy) * currentSkin.skinSize[0]]; + pixelX = x0 + texx * onex + width; + pixelY = y0 + texy * oney + height; + if (pixelY < JAnsi8Engine.C_HEIGHT) + if (pixelX - pixelX % JAnsi8Engine.C_WIDTH == 0) { + newColor = currentSkin.skinData[s0 + texx + (t0 + texy) * currentSkin.skinSize[0]]; if (transparent) { oldColor = colorUnion(hexColorReverse((colorMatrix[pixelX + pixelY * JAnsi8Engine.C_WIDTH] & 0xF0) >> 4)); final float a2 = (newColor >> 24 & 0xFF) / 255f; @@ -451,12 +437,11 @@ public class JAnsi8Renderer implements Renderer { } final int bgColor = colorMatrix[pixelX + pixelY * JAnsi8Engine.C_WIDTH] & 0xF0; colorMatrix[pixelX + pixelY * JAnsi8Engine.C_WIDTH] = bgColor | hexColor(newColor >> 16 & 0xFF, newColor >> 8 & 0xFF, newColor & 0xFF); - if (FILL == 0) initFill(); - charmatrix[pixelX + pixelY * JAnsi8Engine.C_WIDTH] = FILL; + if (JAnsi8Renderer.FILL == 0) + initFill(); + charmatrix[pixelX + pixelY * JAnsi8Engine.C_WIDTH] = JAnsi8Renderer.FILL; } - } } - } } @Override diff --git a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi8colors/JAnsi8Skin.java b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi8colors/JAnsi8Skin.java index 69e2eced..331df018 100644 --- a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi8colors/JAnsi8Skin.java +++ b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jansi8colors/JAnsi8Skin.java @@ -15,43 +15,41 @@ public class JAnsi8Skin implements Skin { public int[] skinData; public int[] skinSize; - JAnsi8Skin(String file) throws IOException { + JAnsi8Skin(final String file) throws IOException { load(file); } @Override - public void load(String file) throws IOException { + public void load(final String file) throws IOException { final BufferedImage img = ImageIO.read(this.getClass().getResource("/" + file)); - skinData = getMatrixOfImage(img); + skinData = JAnsi8Skin.getMatrixOfImage(img); skinSize = new int[] { img.getWidth(), img.getHeight() }; } - public static int[] getMatrixOfImage(BufferedImage bufferedImage) { + public static int[] getMatrixOfImage(final BufferedImage bufferedImage) { BufferedImage after = new BufferedImage(bufferedImage.getWidth(null), bufferedImage.getHeight(null), BufferedImage.TYPE_INT_ARGB); final AffineTransform at = new AffineTransform(); - at.scale(1f / (JAnsi8Engine.C_MUL_X), 1f / (JAnsi8Engine.C_MUL_Y)); + at.scale(1f / JAnsi8Engine.C_MUL_X, 1f / JAnsi8Engine.C_MUL_Y); final AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR); after = scaleOp.filter(bufferedImage, after); final int width = after.getWidth(null); final int height = after.getHeight(null); final int[] pixels = new int[width * height]; - for (int i = 0; i < width; i++) { - for (int j = 0; j < height; j++) { + for (int i = 0; i < width; i++) + for (int j = 0; j < height; j++) pixels[i + j * width] = after.getRGB(i, j); - } - } return pixels; } @Override - public void initialize(GraphicEngine d) { + public void initialize(final GraphicEngine d) { } @Override - public void use(GraphicEngine d) { + public void use(final GraphicEngine d) { ((JAnsi8Renderer) d.getRenderer()).currentSkin = this; } diff --git a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingAdvancedButton.java b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingAdvancedButton.java index fbf3cb8e..7a076600 100644 --- a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingAdvancedButton.java +++ b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingAdvancedButton.java @@ -18,7 +18,7 @@ import javax.swing.JButton; public class SwingAdvancedButton extends JButton { /** - * + * */ private static final long serialVersionUID = -8445811316606975284L; public Image backgroundImage; @@ -28,81 +28,77 @@ public class SwingAdvancedButton extends JButton { public int state; public SwingAdvancedButton() { - this.setOpaque(false); - this.backgroundImage = null; - this.backgroundSize = new Dimension(0, 0); + setOpaque(false); + backgroundImage = null; + backgroundSize = new Dimension(0, 0); } public SwingAdvancedButton(final BufferedImage backgroundImage) throws IOException { - this.setOpaque(false); + setOpaque(false); this.backgroundImage = backgroundImage; - if (backgroundImage != null) { - this.backgroundSize = new Dimension(backgroundImage.getWidth(), backgroundImage.getHeight()); - } - this.setMinimumSize(this.backgroundSize); - this.setMaximumSize(this.backgroundSize); - this.setPreferredSize(this.backgroundSize); - this.setSize(this.backgroundSize); + if (backgroundImage != null) + backgroundSize = new Dimension(backgroundImage.getWidth(), backgroundImage.getHeight()); + setMinimumSize(backgroundSize); + setMaximumSize(backgroundSize); + setPreferredSize(backgroundSize); + this.setSize(backgroundSize); } public SwingAdvancedButton(final BufferedImage backgroundImage, final Dimension backgroundSize) throws IOException { - this.setOpaque(false); + setOpaque(false); this.backgroundImage = backgroundImage; this.backgroundSize = backgroundSize; - this.setMinimumSize(this.backgroundSize); - this.setMaximumSize(this.backgroundSize); - this.setPreferredSize(this.backgroundSize); + setMinimumSize(this.backgroundSize); + setMaximumSize(this.backgroundSize); + setPreferredSize(this.backgroundSize); this.setSize(this.backgroundSize); } + @Override public void paintComponent(final Graphics g) { if (drawColor) { final Graphics2D g2d = (Graphics2D) g.create(); final AlphaComposite acomp = AlphaComposite.getInstance(3, 1.0f); g2d.setComposite(acomp); g2d.setColor(getBackground()); - g2d.fillRect(0, 0, this.getWidth(), this.getHeight()); + g2d.fillRect(0, 0, getWidth(), getHeight()); g2d.dispose(); } - if (this.backgroundImage != null) { + if (backgroundImage != null) { final Graphics2D g2d = (Graphics2D) g.create(); final AlphaComposite acomp = AlphaComposite.getInstance(3, 1.0f); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); g2d.setComposite(acomp); - g2d.drawImage(this.backgroundImage, 0, (int) this.backgroundSize.getHeight() * -state, (int) this.backgroundSize.getWidth(), (int) (this.backgroundSize.getHeight() * 3), null); + g2d.drawImage(backgroundImage, 0, (int) backgroundSize.getHeight() * -state, (int) backgroundSize.getWidth(), (int) (backgroundSize.getHeight() * 3), null); g2d.setFont(g.getFont()); g2d.setColor(super.getForeground()); - g2d.drawString(this.getText(), super.getWidth() / 2 - g.getFontMetrics().stringWidth(this.getText()) / 2, super.getHeight() / 2 + g.getFontMetrics().getHeight() / 4); + g2d.drawString(getText(), super.getWidth() / 2 - g.getFontMetrics().stringWidth(getText()) / 2, super.getHeight() / 2 + g.getFontMetrics().getHeight() / 4); g2d.dispose(); } - if (drawDefaultComponent) { + if (drawDefaultComponent) super.paintComponent(g); - } super.setBorderPainted(drawDefaultComponent); } - + @Override public boolean isEnabled() { - if (canclick == false) { + if (canclick == false) return false; - } return super.isEnabled(); } @Override - public void fireActionPerformed(ActionEvent paramActionEvent) - { - if (this.getCanClick()) { + public void fireActionPerformed(final ActionEvent paramActionEvent) { + if (getCanClick()) super.fireActionPerformed(paramActionEvent); - } - } - - public void setCanClick(boolean can) { + } + + public void setCanClick(final boolean can) { canclick = can; } - + private boolean canclick = true; - + public boolean getCanClick() { return canclick; } diff --git a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingEngine.java b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingEngine.java index 0bcf8a32..bdae8ad3 100644 --- a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingEngine.java +++ b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingEngine.java @@ -22,16 +22,15 @@ public class SwingEngine implements GraphicEngine { public Semaphore exitSemaphore; @Override - public void setTitle(String title) { + public void setTitle(final String title) { INSTANCE.setTitle(title); } @Override - public void setResizable(boolean r) { + public void setResizable(final boolean r) { INSTANCE.setResizable(r); - if (!r) { + if (!r) INSTANCE.setUndecorated(true); - } } @Override @@ -48,7 +47,7 @@ public class SwingEngine implements GraphicEngine { } @Override - public void create(Runnable onInitialized) { + public void create(final Runnable onInitialized) { r = new SwingRenderer(); g = new BufferedImage(r.size[0], r.size[1], BufferedImage.TYPE_INT_RGB); initialized = false; @@ -58,9 +57,8 @@ public class SwingEngine implements GraphicEngine { setDisplayMode(StaticVars.screenSize[0], StaticVars.screenSize[1]); INSTANCE.setVisible(true); initialized = true; - if (onInitialized != null) { + if (onInitialized != null) onInitialized.run(); - } } @Override @@ -87,7 +85,7 @@ public class SwingEngine implements GraphicEngine { } @Override - public void start(RenderingLoop d) { + public void start(final RenderingLoop d) { INSTANCE.setRenderingLoop(d); final Thread th = new Thread(() -> { try { @@ -96,13 +94,12 @@ public class SwingEngine implements GraphicEngine { final long start = System.nanoTime(); repaint(); final long end = System.nanoTime(); - final double delta = (end - start); + final double delta = end - start; if (extratime + delta < 50 * 1000d * 1000d) { Thread.sleep((long) Math.floor(50d - (extratime + delta) / 1000d / 1000d)); extratime = 0; - } else { + } else extratime += delta - 50d; - } } } catch (final InterruptedException e) { e.printStackTrace(); @@ -115,9 +112,8 @@ public class SwingEngine implements GraphicEngine { @Deprecated() public void refresh() { - if (Engine.INSTANCE.getHardwareDevice().getDisplayManager().getScreen() == null || (Engine.INSTANCE.getHardwareDevice().getDisplayManager().error != null && Engine.INSTANCE.getHardwareDevice().getDisplayManager().error.length() > 0) || Engine.INSTANCE.getHardwareDevice().getDisplayManager().getScreen() == null || Engine.INSTANCE.getHardwareDevice().getDisplayManager().getScreen().mustBeRefreshed()) { + if (Engine.INSTANCE.getHardwareDevice().getDisplayManager().getScreen() == null || Engine.INSTANCE.getHardwareDevice().getDisplayManager().error != null && Engine.INSTANCE.getHardwareDevice().getDisplayManager().error.length() > 0 || Engine.INSTANCE.getHardwareDevice().getDisplayManager().getScreen() == null || Engine.INSTANCE.getHardwareDevice().getDisplayManager().getScreen().mustBeRefreshed()) INSTANCE.c.paintImmediately(0, 0, getWidth(), getHeight()); - } } @Override @@ -130,7 +126,7 @@ public class SwingEngine implements GraphicEngine { force = false; } - public Startable(boolean force) { + public Startable(final boolean force) { this.force = force; } @@ -155,17 +151,17 @@ public class SwingEngine implements GraphicEngine { } @Override - public BinaryFont loadFont(String fontName) throws IOException { + public BinaryFont loadFont(final String fontName) throws IOException { return new SwingFont(fontName); } @Override - public BinaryFont loadFont(String path, String fontName) throws IOException { + public BinaryFont loadFont(final String path, final String fontName) throws IOException { return new SwingFont(path, fontName); } @Override - public Skin loadSkin(String file) throws IOException { + public Skin loadSkin(final String file) throws IOException { return new SwingSkin(file); } @@ -178,9 +174,8 @@ public class SwingEngine implements GraphicEngine { @Override public boolean isSupported() { - if (StaticVars.startupArguments.isEngineForced() && StaticVars.startupArguments.isCPUEngineForced() == false) { + if (StaticVars.startupArguments.isEngineForced() && StaticVars.startupArguments.isCPUEngineForced() == false) return false; - } return (StaticVars.startupArguments.isHeadlessEngineForced() || GraphicsEnvironment.isHeadless()) == false; } @@ -189,11 +184,11 @@ public class SwingEngine implements GraphicEngine { return true; } - public void setAlphaChanged(boolean val) { - this.INSTANCE.setAlphaChanged(val); + public void setAlphaChanged(final boolean val) { + INSTANCE.setAlphaChanged(val); } - public void setShiftChanged(boolean val) { - this.INSTANCE.setShiftChanged(val); + public void setShiftChanged(final boolean val) { + INSTANCE.setShiftChanged(val); } } diff --git a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingFont.java b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingFont.java index c1da760e..00266069 100644 --- a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingFont.java +++ b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingFont.java @@ -7,18 +7,17 @@ import it.cavallium.warppi.gui.graphicengine.impl.common.RFTFont; public class SwingFont extends RFTFont { - public SwingFont(String fontName) throws IOException { + public SwingFont(final String fontName) throws IOException { super(fontName); } - public SwingFont(String path, String fontName) throws IOException { + public SwingFont(final String path, final String fontName) throws IOException { super(path, fontName); } @Override - public void use(GraphicEngine d) { - if (d.getRenderer() instanceof SwingRenderer) { + public void use(final GraphicEngine d) { + if (d.getRenderer() instanceof SwingRenderer) ((SwingRenderer) d.getRenderer()).currentFont = this; - } } } diff --git a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingRenderer.java b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingRenderer.java index fbfd88b6..f48d1340 100644 --- a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingRenderer.java +++ b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingRenderer.java @@ -5,6 +5,7 @@ import java.awt.FontMetrics; import it.cavallium.warppi.StaticVars; import it.cavallium.warppi.gui.graphicengine.BinaryFont; import it.cavallium.warppi.gui.graphicengine.Renderer; +import it.cavallium.warppi.gui.graphicengine.impl.common.RFTFont; public class SwingRenderer implements Renderer { public int clearcolor = 0xFFc5c2af; @@ -15,48 +16,47 @@ public class SwingRenderer implements Renderer { static int[] canvas2d = new int[1]; @Override - public void glColor3i(int r, int gg, int b) { + public void glColor3i(final int r, final int gg, final int b) { glColor4i(r, gg, b, 255); } @Override - public void glColor(int c) { + public void glColor(final int c) { color = c & 0xFFFFFFFF; } @Override - public void glClearColor(int c) { + public void glClearColor(final int c) { clearcolor = c & 0xFFFFFFFF; } @Override - public void glColor4i(int red, int green, int blue, int alpha) { - color = (alpha << 24) + (red << 16) + (green << 8) + (blue); + public void glColor4i(final int red, final int green, final int blue, final int alpha) { + color = (alpha << 24) + (red << 16) + (green << 8) + blue; } @Override - public void glClearColor4i(int red, int green, int blue, int alpha) { - clearcolor = (alpha << 24) + (red << 16) + (green << 8) + (blue); + public void glClearColor4i(final int red, final int green, final int blue, final int alpha) { + clearcolor = (alpha << 24) + (red << 16) + (green << 8) + blue; } @Override - public void glClearColor4f(float red, float green, float blue, float alpha) { - clearcolor = ((int) (alpha * 255) << 24) + ((int) (red * 255) << 16) + ((int) (green * 255) << 8) + ((int) (blue * 255)); + public void glClearColor4f(final float red, final float green, final float blue, final float alpha) { + clearcolor = ((int) (alpha * 255) << 24) + ((int) (red * 255) << 16) + ((int) (green * 255) << 8) + (int) (blue * 255); } @Override - public void glClear(int screenWidth, int screenHeight) { - for (int x = 0; x < screenWidth; x++) { + public void glClear(final int screenWidth, final int screenHeight) { + for (int x = 0; x < screenWidth; x++) for (int y = 0; y < screenHeight; y++) { final int index = x + y * size[0]; - if (index >= 0 && index < canvas2d.length) { - canvas2d[index] = clearcolor; - } + if (index >= 0 && index < SwingRenderer.canvas2d.length) + SwingRenderer.canvas2d[index] = clearcolor; } - } } - private void glDrawSkin(int x0, int y0, int x1, int y1, int s0, int t0, int s1, int t1, boolean transparent) { + private void glDrawSkin(int x0, int y0, final int x1, final int y1, int s0, int t0, int s1, int t1, + final boolean transparent) { x0 += StaticVars.screenPos[0]; y0 += StaticVars.screenPos[1]; final double incrementX = Math.abs((double) (x1 - x0) / (double) (s1 - s0)); @@ -81,60 +81,51 @@ public class SwingRenderer implements Renderer { t1 = t00; height = t1 - t0; } - if (x0 >= size[0] || y0 >= size[0]) { + if (x0 >= size[0] || y0 >= size[0]) return; - } - if (x0 + width >= size[0]) { + if (x0 + width >= size[0]) s1 = size[0] - x0 + s0; - } - if (y0 + height >= size[1]) { + if (y0 + height >= size[1]) t1 = size[1] - y0 + t0; - } if (x0 < 0) { if (onex == -1) { width += x0; s1 += x0 + 1; - } else { + } else s0 -= x0; - } x0 = 0; } if (y0 < 0) { if (oney == -1) { height += y0; t1 += y0 + 1; - } else { + } else t0 -= y0; - } y0 = 0; } - for (double pixelX = 0; pixelX < x1 - x0; pixelX++) { + for (double pixelX = 0; pixelX < x1 - x0; pixelX++) for (double pixelY = 0; pixelY < y1 - y0; pixelY++) { final int index = (int) (x0 + pixelX + (y0 + pixelY) * size[0]); - if (index >= 0 && index < canvas2d.length && pixelX < size[0]) { + if (index >= 0 && index < SwingRenderer.canvas2d.length && pixelX < size[0]) { final int texx = (int) (pixelX / incrementX); final int texy = (int) (pixelY / incrementY); int expX = 0; int expY = 0; - if (incrementX < 1) { + if (incrementX < 1) expX = (int) Math.round(1d / incrementX / 2d); - } - if (incrementY < 1) { + if (incrementY < 1) expY = (int) Math.round(1d / incrementY / 2d); - } final int[] newColors = new int[(1 + expX * 2) * (1 + expY * 2)]; - for (int expXi = -expX; expXi <= expX; expXi++) { + for (int expXi = -expX; expXi <= expX; expXi++) for (int expYi = -expY; expYi <= expY; expYi++) { final int skinIndex = (int) (s0 + (texx * (flippedX ? -1d : 1d) + (flippedX ? -(s0 - s1) - 1 : 0) + expXi) + (t0 + (texy * (flippedY ? -1d : 1d) + (flippedY ? -(t0 - t1) - 1 : 0) + expYi)) * currentSkin.skinSize[0]); - final int idx = (expXi + expX) + (expYi + expY) * (1 + expY * 2); - if (idx >= 0 && idx < newColors.length) { + final int idx = expXi + expX + (expYi + expY) * (1 + expY * 2); + if (idx >= 0 && idx < newColors.length) newColors[idx] = getSkinColorAt(currentSkin.skinData, skinIndex); - } } - } newColor = joinColors(newColors); if (transparent) { - oldColor = canvas2d[index]; + oldColor = SwingRenderer.canvas2d[index]; final float a2 = (newColor >> 24 & 0xFF) / 255f; final float a1 = 1f - a2; final int r = (int) ((oldColor >> 16 & 0xFF) * a1 + (newColor >> 16 & 0xFF) * a2); @@ -143,13 +134,12 @@ public class SwingRenderer implements Renderer { newColor = 0xFF000000 | r << 16 | g << 8 | b; } - canvas2d[index] = stackColors(canvas2d[index], newColor); + SwingRenderer.canvas2d[index] = stackColors(SwingRenderer.canvas2d[index], newColor); } } - } } - private int joinColors(int[] newColors) { + private int joinColors(final int[] newColors) { int a = 0; int r = 0; int g = 0; @@ -160,10 +150,10 @@ public class SwingRenderer implements Renderer { g += newColor >> 8 & 0xFF; b += newColor & 0xFF; } - return (a / newColors.length) << 24 | (r / newColors.length) << 16 | (g / newColors.length) << 8 | (b / newColors.length); + return a / newColors.length << 24 | r / newColors.length << 16 | g / newColors.length << 8 | b / newColors.length; } - private int stackColors(int... color) { + private int stackColors(final int... color) { double a = 0; double r = 0; double g = 0; @@ -175,10 +165,10 @@ public class SwingRenderer implements Renderer { g = g * (1d - alpha) + (newColor >> 8 & 0xFF) * alpha; b = b * (1d - alpha) + (newColor & 0xFF) * alpha; } - return ((int) a) << 24 | ((int) r) << 16 | ((int) g) << 8 | ((int) b); + return (int) a << 24 | (int) r << 16 | (int) g << 8 | (int) b; } - private int getSkinColorAt(int[] skinData, int skinIndex) { + private int getSkinColorAt(final int[] skinData, final int skinIndex) { int newColor = 0; if (skinIndex >= 0 && skinIndex < skinData.length) { newColor = skinData[skinIndex]; @@ -201,45 +191,36 @@ public class SwingRenderer implements Renderer { final int ix1 = (int) x1; final int iy0 = (int) y0; final int iy1 = (int) y1; - if (ix0 >= size[0] || iy0 >= size[0]) { + if (ix0 >= size[0] || iy0 >= size[0]) return; - } if (iy0 == iy1) { - for (int x = 0; x <= ix1 - ix0; x++) { - if ((ix0 + x < size[0]) & (iy0 < size[1])) { - canvas2d[ix0 + x + iy0 * size[0]] = stackColors(canvas2d[ix0 + x + iy0 * size[0]], color); - } - } + for (int x = 0; x <= ix1 - ix0; x++) + if (ix0 + x < size[0] & iy0 < size[1]) + SwingRenderer.canvas2d[ix0 + x + iy0 * size[0]] = stackColors(SwingRenderer.canvas2d[ix0 + x + iy0 * size[0]], color); } else if (ix0 == ix1) { - for (int y = 0; y <= iy1 - iy0; y++) { - if ((ix0 < size[0]) & (iy0 + y < size[1])) { - canvas2d[ix0 + (iy0 + y) * size[0]] = stackColors(canvas2d[ix0 + (iy0 + y) * size[0]], color); - } - } + for (int y = 0; y <= iy1 - iy0; y++) + if (ix0 < size[0] & iy0 + y < size[1]) + SwingRenderer.canvas2d[ix0 + (iy0 + y) * size[0]] = stackColors(SwingRenderer.canvas2d[ix0 + (iy0 + y) * size[0]], color); } else { final int m = (iy1 - iy0) / (ix1 - ix0); - for (int texx = 0; texx <= ix1 - ix0; texx++) { - if (ix0 + texx < size[0] && iy0 + (m * texx) < size[1]) { - if ((ix0 + texx < size[0]) & ((iy0 + (m * texx)) < size[1])) { - canvas2d[(ix0 + texx) + (iy0 + (m * texx)) * size[0]] = stackColors(canvas2d[(ix0 + texx) + (iy0 + (m * texx)) * size[0]], color); - } - } - } + for (int texx = 0; texx <= ix1 - ix0; texx++) + if (ix0 + texx < size[0] && iy0 + m * texx < size[1]) + if (ix0 + texx < size[0] & iy0 + m * texx < size[1]) + SwingRenderer.canvas2d[ix0 + texx + (iy0 + m * texx) * size[0]] = stackColors(SwingRenderer.canvas2d[ix0 + texx + (iy0 + m * texx) * size[0]], color); } } @Override - public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth, - float uvHeight) { - if (currentSkin != null) { + public void glFillRect(final float x, final float y, final float width, final float height, final float uvX, + final float uvY, final float uvWidth, final float uvHeight) { + if (currentSkin != null) glDrawSkin((int) x, (int) y, (int) (x + width), (int) (y + height), (int) uvX, (int) uvY, (int) (uvWidth + uvX), (int) (uvHeight + uvY), true); - } else { + else glFillColor(x, y, width, height); - } } @Override - public void glFillColor(float x, float y, float width, float height) { + public void glFillColor(float x, float y, final float width, final float height) { x += StaticVars.screenPos[0]; y += StaticVars.screenPos[1]; @@ -252,34 +233,27 @@ public class SwingRenderer implements Renderer { int y0 = iy; int x1 = ix + iw; int y1 = iy + ih; - if (ix >= size[0] || iy >= size[0]) { + if (ix >= size[0] || iy >= size[0]) return; - } - if (x0 < 0) { + if (x0 < 0) x0 = 0; - } - if (x1 >= size[0]) { + if (x1 >= size[0]) x1 = size[0]; - } - if (y0 < 0) { + if (y0 < 0) y0 = 0; - } - if (y1 >= size[1]) { + if (y1 >= size[1]) y1 = size[1]; - } final int sizeW = size[0]; - for (int px = x0; px < x1; px++) { + for (int px = x0; px < x1; px++) for (int py = y0; py < y1; py++) { - final int idx = (px) + (py) * sizeW; - if (px < sizeW && idx >= 0 && idx < canvas2d.length) { - canvas2d[idx] = stackColors(canvas2d[idx], color); - } + final int idx = px + py * sizeW; + if (px < sizeW && idx >= 0 && idx < SwingRenderer.canvas2d.length) + SwingRenderer.canvas2d[idx] = stackColors(SwingRenderer.canvas2d[idx], color); } - } } @Override - public void glDrawStringLeft(float x, float y, String textString) { + public void glDrawStringLeft(float x, float y, final String textString) { x += StaticVars.screenPos[0]; y += StaticVars.screenPos[1]; @@ -287,7 +261,7 @@ public class SwingRenderer implements Renderer { final int iy = (int) y; final int[] text = currentFont.getCharIndexes(textString); - final int[] screen = canvas2d; + final int[] screen = SwingRenderer.canvas2d; final int[] screenSize = size; final int screenLength = screen.length; int screenPos = 0; @@ -299,41 +273,39 @@ public class SwingRenderer implements Renderer { int j; final int l = text.length; for (int i = 0; i < l; i++) { - cpos = (i * (currentFont.charW)); + cpos = i * currentFont.charW; final int charIndex = text[i]; - for (int dy = 0; dy < currentFont.charH; dy++) { + for (int dy = 0; dy < currentFont.charH; dy++) for (int dx = 0; dx < currentFont.charW; dx++) { j = ix + cpos + dx; if (j > 0 & j < screenSize[0]) { final int bit = dx + dy * currentFont.charW; - currentInt = (int) (Math.floor(bit) / (SwingFont.intBits)); - currentIntBitPosition = bit - (currentInt * SwingFont.intBits); + currentInt = (int) (Math.floor(bit) / RFTFont.intBits); + currentIntBitPosition = bit - currentInt * RFTFont.intBits; final int charIdx = charIndex * currentFont.charIntCount + currentInt; if (charIdx >= 0 && charIdx < currentFont.chars32.length) { - bitData = (currentFont.chars32[charIdx] >> currentIntBitPosition) & 1; + bitData = currentFont.chars32[charIdx] >> currentIntBitPosition & 1; screenPos = ix + cpos + dx + (iy + dy) * screenSize[0]; - if (bitData == 1 & screenLength > screenPos & screenPos >= 0) { + if (bitData == 1 & screenLength > screenPos & screenPos >= 0) screen[screenPos] = stackColors(screen[screenPos], color); - } } } } - } } } @Override - public void glDrawStringCenter(float x, float y, String text) { - glDrawStringLeft(x - (currentFont.getStringWidth(text) / 2), y, text); + public void glDrawStringCenter(final float x, final float y, final String text) { + glDrawStringLeft(x - currentFont.getStringWidth(text) / 2, y, text); } @Override - public void glDrawStringRight(float x, float y, String text) { + public void glDrawStringRight(final float x, final float y, final String text) { glDrawStringLeft(x - currentFont.getStringWidth(text), y, text); } @Deprecated - public int glGetFontWidth(FontMetrics fm, String text) { + public int glGetFontWidth(final FontMetrics fm, final String text) { return fm.stringWidth(text); } @@ -353,12 +325,12 @@ public class SwingRenderer implements Renderer { } @Override - public void glColor3f(float red, float green, float blue) { + public void glColor3f(final float red, final float green, final float blue) { glColor3i((int) (red * 255f), (int) (green * 255f), (int) (blue * 255f)); } @Override - public void glColor4f(float red, float green, float blue, float alpha) { + public void glColor4f(final float red, final float green, final float blue, final float alpha) { glColor4i((int) (red * 255f), (int) (green * 255f), (int) (blue * 255f), (int) (alpha * 255f)); } @@ -368,17 +340,17 @@ public class SwingRenderer implements Renderer { } @Override - public void glDrawCharLeft(int x, int y, char ch) { + public void glDrawCharLeft(final int x, final int y, final char ch) { glDrawStringLeft(x, y, ch + ""); } @Override - public void glDrawCharCenter(int x, int y, char ch) { + public void glDrawCharCenter(final int x, final int y, final char ch) { glDrawStringCenter(x, y, ch + ""); } @Override - public void glDrawCharRight(int x, int y, char ch) { + public void glDrawCharRight(final int x, final int y, final char ch) { glDrawStringRight(x, y, ch + ""); } diff --git a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingSkin.java b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingSkin.java index de0f29f0..9dbddb85 100644 --- a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingSkin.java +++ b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingSkin.java @@ -7,14 +7,13 @@ import it.cavallium.warppi.gui.graphicengine.impl.common.PngSkin; public class SwingSkin extends PngSkin { - public SwingSkin(String file) throws IOException { + public SwingSkin(final String file) throws IOException { super(file); } @Override - public void use(GraphicEngine d) { - if (d.getRenderer() instanceof SwingRenderer) { + public void use(final GraphicEngine d) { + if (d.getRenderer() instanceof SwingRenderer) ((SwingRenderer) d.getRenderer()).currentSkin = this; - } } } diff --git a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingWindow.java b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingWindow.java index f4a2ebc5..0e66dc6e 100644 --- a/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingWindow.java +++ b/desktop/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/swing/SwingWindow.java @@ -11,8 +11,6 @@ import java.awt.GridLayout; import java.awt.Insets; import java.awt.Point; import java.awt.Toolkit; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.KeyEvent; @@ -47,16 +45,16 @@ public class SwingWindow extends JFrame { private RenderingLoop renderingLoop; private final SwingEngine display; private int mult = 1; - private BehaviorSubject onResize; - private Observable onResize$; + private final BehaviorSubject onResize; + private final Observable onResize$; public JPanel buttonsPanel; private SwingAdvancedButton[][] buttons; private int BTN_SIZE; - public SwingWindow(SwingEngine disp) { + public SwingWindow(final SwingEngine disp) { display = disp; - this.setLayout(new BorderLayout()); - this.setBackground(Color.BLACK); + setLayout(new BorderLayout()); + setBackground(Color.BLACK); c = new CustomCanvas(); c.setDoubleBuffered(false); this.add(c, BorderLayout.CENTER); @@ -87,109 +85,106 @@ public class SwingWindow extends JFrame { onResize = BehaviorSubject.create(); onResize$ = onResize.doOnNext((newSize) -> { disp.r.size = new int[] { newSize[0], newSize[1] }; - if (disp.r.size[0] <= 0) { + if (disp.r.size[0] <= 0) disp.r.size[0] = 1; - } - if (disp.r.size[1] <= 0) { + if (disp.r.size[1] <= 0) disp.r.size[1] = 1; - } SwingRenderer.canvas2d = new int[disp.r.size[0] * disp.r.size[1]]; disp.g = new BufferedImage(disp.r.size[0], disp.r.size[1], BufferedImage.TYPE_INT_RGB); }); addComponentListener(new ComponentListener() { @Override - public void componentHidden(ComponentEvent e) { + public void componentHidden(final ComponentEvent e) { Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine.destroy(); } @Override - public void componentMoved(ComponentEvent e) {} + public void componentMoved(final ComponentEvent e) {} @Override - public void componentResized(ComponentEvent e) { + public void componentResized(final ComponentEvent e) { onResize.onNext(new Integer[] { getWidth(), getHeight() }); } @Override - public void componentShown(ComponentEvent e) { - if (Engine.getPlatform().getSettings().isDebugEnabled()) { + public void componentShown(final ComponentEvent e) { + if (Engine.getPlatform().getSettings().isDebugEnabled()) SwingWindow.this.centerWindow(); - } } }); c.setFocusable(true); c.grabFocus(); c.addKeyListener(new KeyListener() { @Override - public void keyPressed(KeyEvent arg0) { + public void keyPressed(final KeyEvent arg0) { Keyboard.debugKeyCode = arg0.getKeyCode(); } @Override - public void keyReleased(KeyEvent arg0) { + public void keyReleased(final KeyEvent arg0) { Keyboard.debugKeyCodeRelease = arg0.getKeyCode(); } @Override - public void keyTyped(KeyEvent arg0) { + public void keyTyped(final KeyEvent arg0) { // TODO Auto-generated method stub } }); c.addMouseMotionListener(new MouseMotionListener() { @Override - public void mouseDragged(MouseEvent e) { + public void mouseDragged(final MouseEvent e) { final Insets wp = SwingWindow.this.getInsets(); - TouchPoint p = new TouchPoint(0, e.getX() - wp.left, e.getY() - wp.top, 5, 5, 1, 0); - ObjectArrayList touches = new ObjectArrayList<>(); - ObjectArrayList changedTouches = new ObjectArrayList<>(); + final TouchPoint p = new TouchPoint(0, e.getX() - wp.left, e.getY() - wp.top, 5, 5, 1, 0); + final ObjectArrayList touches = new ObjectArrayList<>(); + final ObjectArrayList changedTouches = new ObjectArrayList<>(); touches.add(p); changedTouches.add(p); - TouchMoveEvent tse = new TouchMoveEvent(changedTouches, touches); + final TouchMoveEvent tse = new TouchMoveEvent(changedTouches, touches); Engine.INSTANCE.getHardwareDevice().getInputManager().getTouchDevice().onTouchMove(tse); } @Override - public void mouseMoved(MouseEvent e) {} + public void mouseMoved(final MouseEvent e) {} }); c.addMouseListener(new MouseListener() { @Override - public void mouseClicked(MouseEvent e) {} + public void mouseClicked(final MouseEvent e) {} @Override - public void mousePressed(MouseEvent e) { + public void mousePressed(final MouseEvent e) { final Insets wp = SwingWindow.this.getInsets(); - TouchPoint p = new TouchPoint(0, e.getX() - wp.left, e.getY() - wp.top, 5, 5, 1, 0); - ObjectArrayList touches = new ObjectArrayList<>(); - ObjectArrayList changedTouches = new ObjectArrayList<>(); + final TouchPoint p = new TouchPoint(0, e.getX() - wp.left, e.getY() - wp.top, 5, 5, 1, 0); + final ObjectArrayList touches = new ObjectArrayList<>(); + final ObjectArrayList changedTouches = new ObjectArrayList<>(); touches.add(p); changedTouches.add(p); - TouchStartEvent tse = new TouchStartEvent(changedTouches, touches); + final TouchStartEvent tse = new TouchStartEvent(changedTouches, touches); Engine.INSTANCE.getHardwareDevice().getInputManager().getTouchDevice().onTouchStart(tse); } @Override - public void mouseReleased(MouseEvent e) { + public void mouseReleased(final MouseEvent e) { final Insets wp = SwingWindow.this.getInsets(); - TouchPoint p = new TouchPoint(0, e.getX() - wp.left, e.getY() - wp.top, 5, 5, 1, 0); - ObjectArrayList touches = new ObjectArrayList<>(); - ObjectArrayList changedTouches = new ObjectArrayList<>(); + final TouchPoint p = new TouchPoint(0, e.getX() - wp.left, e.getY() - wp.top, 5, 5, 1, 0); + final ObjectArrayList touches = new ObjectArrayList<>(); + final ObjectArrayList changedTouches = new ObjectArrayList<>(); changedTouches.add(p); - TouchEndEvent tse = new TouchEndEvent(changedTouches, touches); + final TouchEndEvent tse = new TouchEndEvent(changedTouches, touches); Engine.INSTANCE.getHardwareDevice().getInputManager().getTouchDevice().onTouchEnd(tse); } @Override - public void mouseEntered(MouseEvent e) {} + public void mouseEntered(final MouseEvent e) {} @Override - public void mouseExited(MouseEvent e) {} + public void mouseExited(final MouseEvent e) {} }); StaticVars.windowZoom$.subscribe((newZoomValue) -> { if (newZoomValue != mult) { mult = (int) newZoomValue.floatValue(); - this.onResize.onNext(new Integer[] { getWWidth(), getWHeight() }); + onResize.onNext(new Integer[] { getWWidth(), getWHeight() }); Engine.getPlatform().getConsoleUtils().out().println(3, "Engine", "CPU", "Zoom changed"); } }); @@ -197,12 +192,11 @@ public class SwingWindow extends JFrame { private void setupButtonsPanel() throws IOException, URISyntaxException { BTN_SIZE = 32; - if (StaticVars.debugWindow2x) { + if (StaticVars.debugWindow2x) BTN_SIZE *= 2; - } - + buttons = new SwingAdvancedButton[8][8]; - JPanel buttonsPanelContainer = new JPanel(); + final JPanel buttonsPanelContainer = new JPanel(); buttonsPanelContainer.setLayout(new FlowLayout()); buttonsPanelContainer.setBackground(Color.BLACK); this.add(buttonsPanelContainer, BorderLayout.PAGE_END); @@ -212,36 +206,32 @@ public class SwingWindow extends JFrame { buttonsPanel.setBackground(Color.GRAY); buttonsPanel.setDoubleBuffered(false); buttonsPanel.setVisible(true); - for (int row = 0; row < 5; row++) { - for (int col = 0; col < 7; col++) { + for (int row = 0; row < 5; row++) + for (int col = 0; col < 7; col++) createBtn(row, col); - } - } for (int row = 5; row < 8; row++) { createBlankBox(); - for (int col = 0; col < 5; col++) { + for (int col = 0; col < 5; col++) createBtn(row, col); - } createBlankBox(); } - int b = 7; + final int b = 7; createBlankBox(); - for (int a = 4; a >= 0; a--) { + for (int a = 4; a >= 0; a--) createBtn(a, b); - } createBlankBox(); } private void createBlankBox() { - JPanel l = new JPanel(); - l.setPreferredSize(new Dimension((int)(BTN_SIZE * 1.5), BTN_SIZE)); + final JPanel l = new JPanel(); + l.setPreferredSize(new Dimension((int) (BTN_SIZE * 1.5), BTN_SIZE)); l.setBackground(Color.BLACK); buttonsPanel.add(l); } - + private void createBtn(final int row, final int col) throws IOException, URISyntaxException { - BufferedImage img = ImageIO.read(Engine.getPlatform().getStorageUtils().getResourceStream("/desktop-buttons.png")); - final SwingAdvancedButton b = new SwingAdvancedButton(img, new Dimension((int)(BTN_SIZE * 1.5), BTN_SIZE)); + final BufferedImage img = ImageIO.read(Engine.getPlatform().getStorageUtils().getResourceStream("/desktop-buttons.png")); + final SwingAdvancedButton b = new SwingAdvancedButton(img, new Dimension((int) (BTN_SIZE * 1.5), BTN_SIZE)); b.drawDefaultComponent = false; b.setText(Keyboard.getKeyName(row, col)); b.setForeground(Color.BLACK); @@ -250,73 +240,61 @@ public class SwingWindow extends JFrame { b.setFont(f); b.setBackground(new Color(200, 200, 200)); b.setFocusable(true); - b.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - Keyboard.keyPressedRaw(row, col); - Keyboard.keyReleasedRaw(row, col); - c.grabFocus(); - } + b.addActionListener(e -> { + Keyboard.keyPressedRaw(row, col); + Keyboard.keyReleasedRaw(row, col); + c.grabFocus(); }); buttons[row][col] = b; buttonsPanel.add(b); } - - public void setAlphaChanged(boolean val) { - for (int row = 0; row < buttons.length; row++) { + + public void setAlphaChanged(final boolean val) { + for (int row = 0; row < buttons.length; row++) for (int col = 0; col < buttons[0].length; col++) { - SwingAdvancedButton btn = buttons[row][col]; + final SwingAdvancedButton btn = buttons[row][col]; if (btn != null) { btn.setText(Keyboard.getKeyName(row, col)); - if (row == 0 && col == 1) { - if (val) { + if (row == 0 && col == 1) + if (val) btn.state = 2; - } else { + else btn.state = 0; - } - } - if (val && Keyboard.hasKeyName(row, col)) { + if (val && Keyboard.hasKeyName(row, col)) btn.setForeground(Color.RED); - } else { + else btn.setForeground(Color.BLACK); - } } } - } } - - public void setShiftChanged(boolean val) { - for (int row = 0; row < buttons.length; row++) { + + public void setShiftChanged(final boolean val) { + for (int row = 0; row < buttons.length; row++) for (int col = 0; col < buttons[0].length; col++) { - SwingAdvancedButton btn = buttons[row][col]; + final SwingAdvancedButton btn = buttons[row][col]; if (btn != null) { btn.setText(Keyboard.getKeyName(row, col)); - if (row == 0 && col == 0) { - if (val) { + if (row == 0 && col == 0) + if (val) btn.state = 2; - } else { + else btn.state = 0; - } - } - if (val && Keyboard.hasKeyName(row, col)) { + if (val && Keyboard.hasKeyName(row, col)) btn.setForeground(new Color(255, 120, 0)); - } else { + else btn.setForeground(Color.BLACK); - } } } - } } - + public Observable onResize() { return onResize$; } @Override - public void setSize(int width, int height) { + public void setSize(final int width, final int height) { c.setSize(new Dimension(width * mult, height * mult)); - c.setPreferredSize(new Dimension(width * mult, height * mult )); + c.setPreferredSize(new Dimension(width * mult, height * mult)); super.pack(); } @@ -332,7 +310,7 @@ public class SwingWindow extends JFrame { return c.getHeight() / mult; } - public void setRenderingLoop(RenderingLoop renderingLoop) { + public void setRenderingLoop(final RenderingLoop renderingLoop) { this.renderingLoop = renderingLoop; } @@ -348,12 +326,12 @@ public class SwingWindow extends JFrame { public class CustomCanvas extends JPanel { /** - * + * */ private static final long serialVersionUID = 605243927485370885L; @Override - public void paintComponent(Graphics g) { + public void paintComponent(final Graphics g) { // long time1 = System.nanoTime(); if (renderingLoop != null) { renderingLoop.refresh(); @@ -375,5 +353,4 @@ public class SwingWindow extends JFrame { } } - } diff --git a/engine-gpu/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jogl/JOGLEngine.java b/engine-gpu/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jogl/JOGLEngine.java index 184cebd6..e95fc6ec 100644 --- a/engine-gpu/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jogl/JOGLEngine.java +++ b/engine-gpu/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jogl/JOGLEngine.java @@ -44,22 +44,21 @@ public class JOGLEngine implements GraphicEngine { } @Override - public void setTitle(String title) { + public void setTitle(final String title) { wnd.window.setTitle(title); } @Override - public void setResizable(boolean r) { - if (!r) { + public void setResizable(final boolean r) { + if (!r) wnd.window.setPosition(0, 0); - } wnd.window.setResizable(r); wnd.window.setUndecorated(!r); wnd.window.setPointerVisible(r); } @Override - public void setDisplayMode(int ww, int wh) { + public void setDisplayMode(final int ww, final int wh) { wnd.setSize(ww, wh); } @@ -69,7 +68,7 @@ public class JOGLEngine implements GraphicEngine { } @Override - public void create(Runnable onInitialized) { + public void create(final Runnable onInitialized) { initialized = false; created = false; size = new int[] { StaticVars.screenSize[0], StaticVars.screenSize[1] }; @@ -111,16 +110,15 @@ public class JOGLEngine implements GraphicEngine { } @Override - public void start(RenderingLoop d) { + public void start(final RenderingLoop d) { this.d = d; wnd.window.setVisible(true); } @Override public void repaint() { - if (d != null & r != null && JOGLRenderer.gl != null) { + if (d != null & r != null && JOGLRenderer.gl != null) d.refresh(); - } } @Override @@ -129,31 +127,27 @@ public class JOGLEngine implements GraphicEngine { } @Override - public BinaryFont loadFont(String name) throws IOException { - for (final Entry entry : fontCache.entrySet()) { - if (entry.getKey().equals(name)) { + public BinaryFont loadFont(final String name) throws IOException { + for (final Entry entry : fontCache.entrySet()) + if (entry.getKey().equals(name)) return entry.getValue(); - } - } final JOGLFont font = new JOGLFont(this, name); fontCache.put(name, font); return font; } @Override - public BinaryFont loadFont(String path, String name) throws IOException { - for (final Entry entry : fontCache.entrySet()) { - if (entry.getKey().equals(name)) { + public BinaryFont loadFont(final String path, final String name) throws IOException { + for (final Entry entry : fontCache.entrySet()) + if (entry.getKey().equals(name)) return entry.getValue(); - } - } final JOGLFont font = new JOGLFont(this, path, name); fontCache.put(name, font); return font; } @Override - public Skin loadSkin(String file) throws IOException { + public Skin loadSkin(final String file) throws IOException { return new JOGLSkin(this, file); } @@ -166,12 +160,10 @@ public class JOGLEngine implements GraphicEngine { @Override public boolean isSupported() { - if (StaticVars.startupArguments.isEngineForced() && StaticVars.startupArguments.isGPUEngineForced() == false) { + if (StaticVars.startupArguments.isEngineForced() && StaticVars.startupArguments.isGPUEngineForced() == false) return false; - } - if (StaticVars.startupArguments.isHeadlessEngineForced()) { + if (StaticVars.startupArguments.isHeadlessEngineForced()) return false; - } boolean available = false; boolean errored = false; try { @@ -180,9 +172,8 @@ public class JOGLEngine implements GraphicEngine { errored = true; System.err.println("OpenGL Error: " + ex.getMessage()); } - if (!available && !errored) { + if (!available && !errored) System.err.println(GLProfile.glAvailabilityToString()); - } return available; } @@ -191,7 +182,7 @@ public class JOGLEngine implements GraphicEngine { return false; } - public void registerFont(JOGLFont gpuFont) { + public void registerFont(final JOGLFont gpuFont) { registeredFonts.add(gpuFont); } @@ -205,7 +196,7 @@ public class JOGLEngine implements GraphicEngine { return registeredFonts; } - public void registerTexture(Texture t) { + public void registerTexture(final Texture t) { unregisteredTextures.addLast(t); } diff --git a/engine-gpu/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jogl/JOGLFont.java b/engine-gpu/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jogl/JOGLFont.java index cb49f042..3db2befa 100644 --- a/engine-gpu/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jogl/JOGLFont.java +++ b/engine-gpu/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jogl/JOGLFont.java @@ -35,27 +35,26 @@ public class JOGLFont implements BinaryFont { private boolean initialized = false; private File tmpFont; - JOGLFont(GraphicEngine g, String name) throws IOException { + JOGLFont(final GraphicEngine g, final String name) throws IOException { this(g, null, name); } - public JOGLFont(GraphicEngine g, String path, String name) throws IOException { + public JOGLFont(final GraphicEngine g, final String path, final String name) throws IOException { load(path, name); ((JOGLEngine) g).registerFont(this); } @Override - public void load(String name) throws IOException { + public void load(final String name) throws IOException { load(null, name); } - public void load(String path, String name) throws IOException { + public void load(final String path, final String name) throws IOException { RFTFont font; - if (path == null) { + if (path == null) font = RFTFont.loadTemporaryFont(name); - } else { + else font = RFTFont.loadTemporaryFont(path, name); - } charW = font.charW; charH = font.charH; minCharIndex = font.minBound; @@ -70,7 +69,7 @@ public class JOGLFont implements BinaryFont { Engine.getPlatform().gc(); } - public int[] getCharIndexes(String txt) { + public int[] getCharIndexes(final String txt) { final int[] indexes = new int[txt.length()]; int i = 0; for (final char c : txt.toCharArray()) { @@ -80,57 +79,54 @@ public class JOGLFont implements BinaryFont { return indexes; } - public int getCharIndex(char c) { + public int getCharIndex(final char c) { final int originalIndex = c & 0xFFFF; return compressIndex(originalIndex); } - private int compressIndex(int originalIndex) { + private int compressIndex(final int originalIndex) { int compressedIndex = 0; - for (int i = 0; i < intervals.length; i += 3) { - if (intervals[i] > originalIndex) { + for (int i = 0; i < intervals.length; i += 3) + if (intervals[i] > originalIndex) break; - } else if (originalIndex <= intervals[i + 1]) { - compressedIndex += (originalIndex - intervals[i]); + else if (originalIndex <= intervals[i + 1]) { + compressedIndex += originalIndex - intervals[i]; break; - } else { + } else compressedIndex += intervals[i + 2]; - } - } return compressedIndex; } @SuppressWarnings("unused") - private int decompressIndex(int compressedIndex) { + private int decompressIndex(final int compressedIndex) { final int originalIndex = 0; int i = 0; for (final int intvl = 0; i < intervals.length; i += 3) { i += intervals[intvl + 2]; - if (i >= compressedIndex) { + if (i >= compressedIndex) return intervals[intvl + 1] - (i - compressedIndex); - } } return originalIndex; } private void pregenTexture(boolean[][] chars) throws IOException { final int totalChars = intervalsTotalSize; - int w = powerOf2((int) (Math.ceil(Math.sqrt(totalChars) * charW))); - int h = powerOf2((int) (Math.ceil(Math.sqrt(totalChars) * charH))); - int maxIndexW = (int) Math.floor(((double) w) / ((double) charW)) - 1; - int maxIndexH = (int) Math.floor(((double) h) / ((double) charH)) - 1; + int w = powerOf2((int) Math.ceil(Math.sqrt(totalChars) * charW)); + int h = powerOf2((int) Math.ceil(Math.sqrt(totalChars) * charH)); + int maxIndexW = (int) Math.floor((double) w / (double) charW) - 1; + int maxIndexH = (int) Math.floor((double) h / (double) charH) - 1; if (w > h) { System.out.println("w > h"); - h = powerOf2((int) (Math.ceil((((double) totalChars) / ((double) (maxIndexW))) * charH))); - maxIndexH = (int) Math.floor(((double) h) / ((double) charH)) - 1; + h = powerOf2((int) Math.ceil((double) totalChars / (double) maxIndexW * charH)); + maxIndexH = (int) Math.floor((double) h / (double) charH) - 1; } else { System.out.println("w <= h"); - w = powerOf2((int) (Math.ceil((((double) totalChars) / ((double) (maxIndexH))) * charW))); - maxIndexW = (int) Math.floor(((double) w) / ((double) charW)) - 1; + w = powerOf2((int) Math.ceil((double) totalChars / (double) maxIndexH * charW)); + maxIndexW = (int) Math.floor((double) w / (double) charW) - 1; } // final int h = powerOf2((int) (Math.ceil(Math.sqrt(totalChars) * charH))); - System.out.println(((int) Math.ceil(Math.sqrt(totalChars) * charW)) + " * " + ((int) Math.ceil(Math.sqrt(totalChars) * charH)) + " --> " + w + " * " + h); + System.out.println((int) Math.ceil(Math.sqrt(totalChars) * charW) + " * " + (int) Math.ceil(Math.sqrt(totalChars) * charH) + " --> " + w + " * " + h); final File f = Files.createTempFile("texture-font-", ".png").toFile(); f.deleteOnExit(); @@ -142,23 +138,18 @@ public class JOGLFont implements BinaryFont { final ImageLineInt iline = new ImageLineInt(imi); final int[] xValues = new int[imi.cols]; for (int indexX = 0; indexX <= maxIndexW; indexX++) {// this line will be written to all rows - final int charY = (y % charH); + final int charY = y % charH; final int indexY = (y - charY) / charH; final int i = indexY * (maxIndexW + 1) + indexX - minCharIndex; boolean[] currentChar; - if (i < totalChars && (currentChar = chars[i]) != null) { - for (int charX = 0; charX < charW; charX++) { - if (i >= 0 & i < totalChars && currentChar != null && currentChar[charX + charY * charW]) { + if (i < totalChars && (currentChar = chars[i]) != null) + for (int charX = 0; charX < charW; charX++) + if (i >= 0 & i < totalChars && currentChar != null && currentChar[charX + charY * charW]) xValues[indexX * charW + charX] = 0xFFFFFFFF; - } -// ImageLineHelper.setPixelRGBA8(iline, x, color, color, color, color); - } - } } ImageLineHelper.setPixelsRGBA8(iline, xValues); - if (y % 10 == 0) { + if (y % 10 == 0) System.out.println(y + "/" + png.imgInfo.rows); - } png.writeRow(iline); } chars = null; @@ -189,35 +180,33 @@ public class JOGLFont implements BinaryFont { } } - private int powerOf2(int i) { + private int powerOf2(final int i) { return i > 1 ? Integer.highestOneBit(i - 1) << 1 : 1; } @Override - public void initialize(GraphicEngine d) { + public void initialize(final GraphicEngine d) { genTexture(); tmpFont = null; initialized = true; } @Override - public void use(GraphicEngine d) { - if (!initialized) { + public void use(final GraphicEngine d) { + if (!initialized) initialize(d); - } final JOGLRenderer r = (JOGLRenderer) d.getRenderer(); r.currentFont = this; r.useTexture(texture, textureW, textureH); } @Override - public int getStringWidth(String text) { - final int w = (charW) * text.length(); - if (text.length() > 0) { + public int getStringWidth(final String text) { + final int w = charW * text.length(); + if (text.length() > 0) return w; - } else { + else return 0; - } } @Override diff --git a/engine-gpu/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jogl/JOGLRenderer.java b/engine-gpu/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jogl/JOGLRenderer.java index 6135093a..9c2817e3 100644 --- a/engine-gpu/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jogl/JOGLRenderer.java +++ b/engine-gpu/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jogl/JOGLRenderer.java @@ -40,11 +40,11 @@ public class JOGLRenderer implements Renderer { private static final int colBuffer = 2; - private static final int vertMax = vertSize * ELEMENT_VERTICES_COUNT * ELEMENTS_MAX_COUNT_PER_BUFFER; + private static final int vertMax = JOGLRenderer.vertSize * JOGLRenderer.ELEMENT_VERTICES_COUNT * JOGLRenderer.ELEMENTS_MAX_COUNT_PER_BUFFER; - private static final int texMax = texSize * ELEMENT_VERTICES_COUNT * ELEMENTS_MAX_COUNT_PER_BUFFER; + private static final int texMax = JOGLRenderer.texSize * JOGLRenderer.ELEMENT_VERTICES_COUNT * JOGLRenderer.ELEMENTS_MAX_COUNT_PER_BUFFER; - private static final int colMax = colSize * ELEMENT_VERTICES_COUNT * ELEMENTS_MAX_COUNT_PER_BUFFER; + private static final int colMax = JOGLRenderer.colSize * JOGLRenderer.ELEMENT_VERTICES_COUNT * JOGLRenderer.ELEMENTS_MAX_COUNT_PER_BUFFER; private int[] handlers; FloatBuffer fbVertices; @@ -62,32 +62,32 @@ public class JOGLRenderer implements Renderer { JOGLFont currentFont; @Override - public void glColor3i(int r, int gg, int b) { - final float red = (r) / 255f; - final float gre = (gg) / 255f; - final float blu = (b) / 255f; + public void glColor3i(final int r, final int gg, final int b) { + final float red = r / 255f; + final float gre = gg / 255f; + final float blu = b / 255f; //currentColor = new float[] { red, gre, blu, 1.0f, red, gre, blu, 1.0f, red, gre, blu, 1.0f, red, gre, blu, 1.0f, }; currentColor = new float[] { red, gre, blu, 1.0f, red, gre, blu, 1.0f, red, gre, blu, 1.0f, red, gre, blu, 1.0f, red, gre, blu, 1.0f, red, gre, blu, 1.0f, }; //OK } @Override - public void glColor3f(float red, float gre, float blu) { + public void glColor3f(final float red, final float gre, final float blu) { // currentColor = new float[] { red, gre, blu, 1.0f, red, gre, blu, 1.0f, red, gre, blu, 1.0f, red, gre, blu, 1.0f, }; currentColor = new float[] { red, gre, blu, 1.0f, red, gre, blu, 1.0f, red, gre, blu, 1.0f, red, gre, blu, 1.0f, red, gre, blu, 1.0f, red, gre, blu, 1.0f, };//OK } @Override - public void glColor4f(float red, float gre, float blu, float alp) { + public void glColor4f(final float red, final float gre, final float blu, final float alp) { // currentColor = new float[] { red, gre, blu, alp, red, gre, blu, alp, red, gre, blu, alp, red, gre, blu, alp, }; currentColor = new float[] { red, gre, blu, alp, red, gre, blu, alp, red, gre, blu, alp, red, gre, blu, alp, red, gre, blu, alp, red, gre, blu, alp, };//ok } @Override - public void glColor(int rgb) { - final int alpha = (rgb >> 24) & 0xFF; - final int red = (rgb >> 16) & 0xFF; - final int green = (rgb >> 8) & 0xFF; + public void glColor(final int rgb) { + final int alpha = rgb >> 24 & 0xFF; + final int red = rgb >> 16 & 0xFF; + final int green = rgb >> 8 & 0xFF; final int blue = rgb & 0xFF; glColor4i(red, green, blue, alpha); } @@ -98,59 +98,57 @@ public class JOGLRenderer implements Renderer { } @Override - public void glClearColor(int rgb) { - final float alpha = ((rgb >> 24) & 0xFF) / 255f; - final float red = ((rgb >> 16) & 0xFF) / 255f; - final float green = ((rgb >> 8) & 0xFF) / 255f; + public void glClearColor(final int rgb) { + final float alpha = (rgb >> 24 & 0xFF) / 255f; + final float red = (rgb >> 16 & 0xFF) / 255f; + final float green = (rgb >> 8 & 0xFF) / 255f; final float blue = (rgb & 0xFF) / 255f; glClearColor4f(red, green, blue, alpha); } @Override - public void glColor4i(int r, int g, int b, int a) { - final float red = (r) / 255f; - final float gre = (g) / 255f; - final float blu = (b) / 255f; - final float alp = (a) / 255f; + public void glColor4i(final int r, final int g, final int b, final int a) { + final float red = r / 255f; + final float gre = g / 255f; + final float blu = b / 255f; + final float alp = a / 255f; //currentColor = new float[] { red, gre, blu, alp, red, gre, blu, alp, red, gre, blu, alp, red, gre, blu, alp, }; currentColor = new float[] { red, gre, blu, alp, red, gre, blu, alp, red, gre, blu, alp, red, gre, blu, alp, red, gre, blu, alp, red, gre, blu, alp, };//OK } @Override - public void glClearColor4i(int red, int green, int blue, int alpha) { - final float ros = (red) / 255f; - final float gre = (green) / 255f; - final float blu = (blue) / 255f; - final float alp = (alpha) / 255f; + public void glClearColor4i(final int red, final int green, final int blue, final int alpha) { + final float ros = red / 255f; + final float gre = green / 255f; + final float blu = blue / 255f; + final float alp = alpha / 255f; currentClearColorARGBf = new float[] { alp, ros, gre, blu }; } @Override - public void glClearColor4f(float red, float green, float blue, float alpha) { + public void glClearColor4f(final float red, final float green, final float blue, final float alpha) { currentClearColorARGBf = new float[] { alpha, red, green, blue }; } @Override - public void glClear(int screenWidth, int screenHeight) { + public void glClear(final int screenWidth, final int screenHeight) { glColor(glGetClearColor()); glFillColor(0, 0, screenWidth, screenHeight); } @Override - public void glDrawLine(float x0, float y0, float x1, float y1) { + public void glDrawLine(final float x0, final float y0, final float x1, final float y1) { glFillColor(x0, y0, x1 - x0 + 1, y1 - y0 + 1); } @Override - public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth, - float uvHeight) { + public void glFillRect(final float x, final float y, final float width, final float height, float uvX, float uvY, + float uvWidth, float uvHeight) { enableTexture(); - if (uvWidth < 0) { + if (uvWidth < 0) uvX -= uvWidth; - } - if (uvHeight < 0) { + if (uvHeight < 0) uvY -= uvHeight; - } uvWidth /= currentTexWidth; uvX /= currentTexWidth; uvHeight /= currentTexHeight; @@ -179,7 +177,7 @@ public class JOGLRenderer implements Renderer { } @Override - public void glFillColor(float x0, float y0, float w1, float h1) { + public void glFillColor(final float x0, final float y0, final float w1, final float h1) { disableTexture(); // final float[] vertices = { x0, y0, 0.0f, x0, y0 + h1, 0.0f, x0 + w1, y0, 0.0f, x0 + w1, y0 + h1, 0.0f, }; // final float[] tex_vertices = { 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, }; @@ -205,7 +203,7 @@ public class JOGLRenderer implements Renderer { } @Override - public void glDrawStringLeft(float x, float y, String text) { + public void glDrawStringLeft(final float x, final float y, final String text) { final int txtLen = text.length(); final int[] txtArray = currentFont.getCharIndexes(text); int tableIndexX; @@ -213,22 +211,22 @@ public class JOGLRenderer implements Renderer { for (int currentCharIndex = 0; currentCharIndex < txtLen; currentCharIndex++) { tableIndexX = txtArray[currentCharIndex] % currentFont.memoryWidthOfEachColumn; tableIndexY = (txtArray[currentCharIndex] - tableIndexX) / currentFont.memoryWidthOfEachColumn; - glFillRect(x + ((float) currentCharIndex) * ((float) (currentFont.charW)), y, currentFont.charW, currentFont.charH, tableIndexX * currentFont.charW, tableIndexY * currentFont.charH, currentFont.charW, currentFont.charH); + glFillRect(x + (float) currentCharIndex * (float) currentFont.charW, y, currentFont.charW, currentFont.charH, tableIndexX * currentFont.charW, tableIndexY * currentFont.charH, currentFont.charW, currentFont.charH); } } @Override - public void glDrawStringCenter(float x, float y, String text) { - glDrawStringLeft(x - (currentFont.getStringWidth(text) / 2), y, text); + public void glDrawStringCenter(final float x, final float y, final String text) { + glDrawStringLeft(x - currentFont.getStringWidth(text) / 2, y, text); } @Override - public void glDrawStringRight(float x, float y, String text) { + public void glDrawStringRight(final float x, final float y, final String text) { glDrawStringLeft(x - currentFont.getStringWidth(text), y, text); } @Override - public void glDrawCharLeft(int x, int y, char ch) { + public void glDrawCharLeft(final int x, final int y, final char ch) { final int index = currentFont.getCharIndex(ch); final int tableIndexX = index % currentFont.memoryWidthOfEachColumn; final int tableIndexY = (index - tableIndexX) / currentFont.memoryWidthOfEachColumn; @@ -236,12 +234,12 @@ public class JOGLRenderer implements Renderer { } @Override - public void glDrawCharCenter(int x, int y, char ch) { - glDrawCharLeft(x - (currentFont.charW / 2), y, ch); + public void glDrawCharCenter(final int x, final int y, final char ch) { + glDrawCharLeft(x - currentFont.charW / 2, y, ch); } @Override - public void glDrawCharRight(int x, int y, char ch) { + public void glDrawCharRight(final int x, final int y, final char ch) { glDrawCharLeft(x - currentFont.charW, y, ch); } @@ -251,7 +249,7 @@ public class JOGLRenderer implements Renderer { } @Deprecated - static Texture importTexture(GL gl, String string) throws IOException { + static Texture importTexture(final GL gl, final String string) throws IOException { final FileInputStream f = new FileInputStream("test.png"); final TextureData tx_dat = TextureIO.newTextureData(gl.getGLProfile(), f, false, TextureIO.PNG); final Texture tex = new Texture(gl, tx_dat); @@ -262,16 +260,15 @@ public class JOGLRenderer implements Renderer { return tex; } - static OpenedTextureData openTexture(String file, boolean isResource) throws GLException, IOException { + static OpenedTextureData openTexture(final String file, final boolean isResource) throws GLException, IOException { BufferedImage img = ImageIO.read(isResource ? JOGLRenderer.class.getResource("/" + file) : new File(file).toURI().toURL()); File f; if (isResource) { f = Files.createTempFile("texture-", ".png").toFile(); f.deleteOnExit(); ImageIO.write(img, "png", f); - } else { + } else f = new File(file); - } final int imgW = img.getWidth(); final int imgH = img.getHeight(); img = null; @@ -291,7 +288,7 @@ public class JOGLRenderer implements Renderer { * @param f * @param deleteOnExit */ - public OpenedTextureData(int w, int h, File f, boolean deleteOnExit) { + public OpenedTextureData(final int w, final int h, final File f, final boolean deleteOnExit) { this.w = w; this.h = h; this.f = f; @@ -300,20 +297,18 @@ public class JOGLRenderer implements Renderer { } - static Texture importTexture(File f, boolean deleteOnExit) throws GLException, IOException { + static Texture importTexture(File f, final boolean deleteOnExit) throws GLException, IOException { final Texture tex = TextureIO.newTexture(f, false); - if (deleteOnExit && f.exists()) { + if (deleteOnExit && f.exists()) try { - if (Engine.getPlatform().getSettings().isDebugEnabled()) { + if (Engine.getPlatform().getSettings().isDebugEnabled()) throw new IOException("Delete on exit!"); - } f.delete(); } catch (final Exception ex) { f.deleteOnExit(); } - } - tex.setTexParameteri(gl, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST); - tex.setTexParameteri(gl, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST); + tex.setTexParameteri(JOGLRenderer.gl, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST); + tex.setTexParameteri(JOGLRenderer.gl, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST); f = null; return tex; } @@ -321,48 +316,41 @@ public class JOGLRenderer implements Renderer { public void initDrawCycle() { final boolean textureChange = precTexEnabled != currentTexEnabled || precTex != currentTex; if (fbVertices == null) { - fbVertices = Buffers.newDirectFloatBuffer(vertMax); - fbTextures = Buffers.newDirectFloatBuffer(texMax); - fbColors = Buffers.newDirectFloatBuffer(colMax); + fbVertices = Buffers.newDirectFloatBuffer(JOGLRenderer.vertMax); + fbTextures = Buffers.newDirectFloatBuffer(JOGLRenderer.texMax); + fbColors = Buffers.newDirectFloatBuffer(JOGLRenderer.colMax); handlers = new int[3]; - gl.glGenBuffers(3, handlers, 0); + JOGLRenderer.gl.glGenBuffers(3, handlers, 0); } startDrawSegment(false); - if (textureChange) { + if (textureChange) changeTexture(); - } } public void endDrawCycle() { final boolean textureChange = precTexEnabled != currentTexEnabled || precTex != currentTex; if (textureChange) { - if (fbElements > 0) { + if (fbElements > 0) endDrawSegment(); - } changeTexture(); - } else { - if (fbElements > 0) { - endDrawSegment(); - } - } + } else if (fbElements > 0) + endDrawSegment(); } private void changeTexture() { precTexEnabled = currentTexEnabled; precTex = currentTex; if (currentTexEnabled) { - gl.glEnable(GL.GL_TEXTURE_2D); - currentTex.bind(gl); - } else { - gl.glDisable(GL.GL_TEXTURE_2D); - } + JOGLRenderer.gl.glEnable(GL.GL_TEXTURE_2D); + currentTex.bind(JOGLRenderer.gl); + } else + JOGLRenderer.gl.glDisable(GL.GL_TEXTURE_2D); firstBufferTexDataCall = true; } - public void startDrawSegment(boolean continuation) { - if (!continuation || cycleEnded) { + public void startDrawSegment(final boolean continuation) { + if (!continuation || cycleEnded) fbElements = 0; - } cycleEnded = false; } @@ -372,18 +360,16 @@ public class JOGLRenderer implements Renderer { public void doDrawSegment() { final boolean textureChange = precTexEnabled != currentTexEnabled || precTex != currentTex; - final boolean changeRequired = fbElements >= ELEMENTS_MAX_COUNT_PER_BUFFER; + final boolean changeRequired = fbElements >= JOGLRenderer.ELEMENTS_MAX_COUNT_PER_BUFFER; if (textureChange) { if (fbElements > 0) { endDrawSegment(); startDrawSegment(false); } changeTexture(); - } else { - if (fbElements > 0 && changeRequired) { - endDrawSegment(); - startDrawSegment(true); - } + } else if (fbElements > 0 && changeRequired) { + endDrawSegment(); + startDrawSegment(true); } } @@ -396,34 +382,31 @@ public class JOGLRenderer implements Renderer { fbColors.flip(); // gl.glVertexPointer(vertSize, GL.GL_FLOAT, 0, fbVertices); - gl.glBindBuffer(GL.GL_ARRAY_BUFFER, handlers[vertBuffer]); - if (firstBufferTexDataCall) { - gl.glBufferData(GL.GL_ARRAY_BUFFER, fbVertices.limit() * Buffers.SIZEOF_FLOAT, fbVertices, GL.GL_STATIC_DRAW); - } else { - gl.glBufferSubData(GL.GL_ARRAY_BUFFER, 0, fbVertices.limit() * Buffers.SIZEOF_FLOAT, fbVertices); - } - gl.glVertexPointer(vertSize, GL.GL_FLOAT, 0, 0l); + JOGLRenderer.gl.glBindBuffer(GL.GL_ARRAY_BUFFER, handlers[JOGLRenderer.vertBuffer]); + if (firstBufferTexDataCall) + JOGLRenderer.gl.glBufferData(GL.GL_ARRAY_BUFFER, fbVertices.limit() * Buffers.SIZEOF_FLOAT, fbVertices, GL.GL_STATIC_DRAW); + else + JOGLRenderer.gl.glBufferSubData(GL.GL_ARRAY_BUFFER, 0, fbVertices.limit() * Buffers.SIZEOF_FLOAT, fbVertices); + JOGLRenderer.gl.glVertexPointer(JOGLRenderer.vertSize, GL.GL_FLOAT, 0, 0l); // gl.glTexCoordPointer(texSize, GL.GL_FLOAT, 0, fbTextures); - gl.glBindBuffer(GL.GL_ARRAY_BUFFER, handlers[texBuffer]); - if (firstBufferTexDataCall) { - gl.glBufferData(GL.GL_ARRAY_BUFFER, fbTextures.limit() * Buffers.SIZEOF_FLOAT, fbTextures, GL.GL_STATIC_DRAW); - } else { - gl.glBufferSubData(GL.GL_ARRAY_BUFFER, 0, fbTextures.limit() * Buffers.SIZEOF_FLOAT, fbTextures); - } - gl.glTexCoordPointer(texSize, GL.GL_FLOAT, 0, 0l); + JOGLRenderer.gl.glBindBuffer(GL.GL_ARRAY_BUFFER, handlers[JOGLRenderer.texBuffer]); + if (firstBufferTexDataCall) + JOGLRenderer.gl.glBufferData(GL.GL_ARRAY_BUFFER, fbTextures.limit() * Buffers.SIZEOF_FLOAT, fbTextures, GL.GL_STATIC_DRAW); + else + JOGLRenderer.gl.glBufferSubData(GL.GL_ARRAY_BUFFER, 0, fbTextures.limit() * Buffers.SIZEOF_FLOAT, fbTextures); + JOGLRenderer.gl.glTexCoordPointer(JOGLRenderer.texSize, GL.GL_FLOAT, 0, 0l); // gl.glColorPointer(colSize, GL.GL_FLOAT, 0, fbColors); - gl.glBindBuffer(GL.GL_ARRAY_BUFFER, handlers[colBuffer]); - if (firstBufferTexDataCall) { - gl.glBufferData(GL.GL_ARRAY_BUFFER, fbColors.limit() * Buffers.SIZEOF_FLOAT, fbColors, GL.GL_STATIC_DRAW); - } else { - gl.glBufferSubData(GL.GL_ARRAY_BUFFER, 0, fbColors.limit() * Buffers.SIZEOF_FLOAT, fbColors); - } - gl.glColorPointer(colSize, GL.GL_FLOAT, 0, 0l); + JOGLRenderer.gl.glBindBuffer(GL.GL_ARRAY_BUFFER, handlers[JOGLRenderer.colBuffer]); + if (firstBufferTexDataCall) + JOGLRenderer.gl.glBufferData(GL.GL_ARRAY_BUFFER, fbColors.limit() * Buffers.SIZEOF_FLOAT, fbColors, GL.GL_STATIC_DRAW); + else + JOGLRenderer.gl.glBufferSubData(GL.GL_ARRAY_BUFFER, 0, fbColors.limit() * Buffers.SIZEOF_FLOAT, fbColors); + JOGLRenderer.gl.glColorPointer(JOGLRenderer.colSize, GL.GL_FLOAT, 0, 0l); - fbVertices.limit(vertMax); - fbTextures.limit(texMax); - fbColors.limit(colMax); - gl.glDrawArrays(GL.GL_TRIANGLES, 0, fbElements * ELEMENT_VERTICES_COUNT); + fbVertices.limit(JOGLRenderer.vertMax); + fbTextures.limit(JOGLRenderer.texMax); + fbColors.limit(JOGLRenderer.colMax); + JOGLRenderer.gl.glDrawArrays(GL.GL_TRIANGLES, 0, fbElements * JOGLRenderer.ELEMENT_VERTICES_COUNT); //gl.glDrawArrays(GL.GL_TRIANGLE_STRIP, 0, fbElements * ELEMENT_VERTICES_COUNT); firstBufferDataCall = false; firstBufferTexDataCall = false; @@ -455,7 +438,7 @@ public class JOGLRenderer implements Renderer { doDrawSegment(); } - void useTexture(Texture t, float w, float h) { + void useTexture(final Texture t, final float w, final float h) { currentTex = t; currentTexWidth = w; currentTexHeight = h; diff --git a/engine-gpu/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jogl/JOGLSkin.java b/engine-gpu/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jogl/JOGLSkin.java index acbe94bc..1361202c 100644 --- a/engine-gpu/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jogl/JOGLSkin.java +++ b/engine-gpu/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jogl/JOGLSkin.java @@ -21,22 +21,21 @@ public class JOGLSkin implements Skin { private boolean initialized = false; private boolean isResource; - JOGLSkin(GraphicEngine d, String file) throws IOException { + JOGLSkin(final GraphicEngine d, final String file) throws IOException { load(file); } @Override - public void load(String file) throws IOException { + public void load(final String file) throws IOException { final boolean isResource = !Files.exists(Paths.get(file)); - if (isResource && (this.getClass().getClassLoader().getResource(file)) == null) { + if (isResource && this.getClass().getClassLoader().getResource(file) == null) throw new IOException("File '" + file + "' not found!"); - } texturePath = file; this.isResource = isResource; } @Override - public void initialize(GraphicEngine d) { + public void initialize(final GraphicEngine d) { try { final OpenedTextureData i = JOGLRenderer.openTexture(texturePath, isResource); t = JOGLRenderer.importTexture(i.f, i.deleteOnExit); @@ -51,10 +50,9 @@ public class JOGLSkin implements Skin { } @Override - public void use(GraphicEngine d) { - if (!initialized) { + public void use(final GraphicEngine d) { + if (!initialized) initialize(d); - } final JOGLRenderer r = (JOGLRenderer) d.getRenderer(); r.useTexture(t, w, h); } diff --git a/engine-gpu/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jogl/NEWTWindow.java b/engine-gpu/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jogl/NEWTWindow.java index 09f8fa7a..93a52ea2 100644 --- a/engine-gpu/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jogl/NEWTWindow.java +++ b/engine-gpu/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/jogl/NEWTWindow.java @@ -83,10 +83,10 @@ class NEWTWindow implements GLEventListener { final BehaviorSubject onRealResize; final BehaviorSubject onResizeEvent = BehaviorSubject.create(); - private BehaviorSubject onZoom = BehaviorSubject.create(); - private Subject onGLContext = SimpleSubject.create(); + private final BehaviorSubject onZoom = BehaviorSubject.create(); + private final Subject onGLContext = SimpleSubject.create(); - public NEWTWindow(JOGLEngine disp) { + public NEWTWindow(final JOGLEngine disp) { this.disp = disp; renderer = disp.getRenderer(); disp.size[0] = StaticVars.screenSize[0]; @@ -133,9 +133,8 @@ class NEWTWindow implements GLEventListener { System.err.println("Le OpenGL non sono presenti su questo computer!"); return; } - if (Engine.getPlatform().getSettings().isDebugEnabled()) { + if (Engine.getPlatform().getSettings().isDebugEnabled()) System.setProperty("jnlp.newt.window.icons", "res/icons/calculator-016.png res/icons/calculator-018.png res/icons/calculator-256.png"); - } final GLCapabilities caps = new GLCapabilities(GLProfile.get(GLProfile.GL2ES1)); System.out.println("Loaded OpenGL"); // We may at this point tweak the caps and request a translucent drawable @@ -152,57 +151,56 @@ class NEWTWindow implements GLEventListener { glWindow.addWindowListener(new WindowListener() { @Override - public void windowDestroyNotify(WindowEvent e) { + public void windowDestroyNotify(final WindowEvent e) { // TODO Auto-generated method stub } @Override - public void windowDestroyed(WindowEvent e) { - GraphicEngine engine = Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine; - if (engine.isInitialized()) { + public void windowDestroyed(final WindowEvent e) { + final GraphicEngine engine = Engine.INSTANCE.getHardwareDevice().getDisplayManager().engine; + if (engine.isInitialized()) engine.destroy(); - } } @Override - public void windowGainedFocus(WindowEvent e) { + public void windowGainedFocus(final WindowEvent e) { // TODO Auto-generated method stub } @Override - public void windowLostFocus(WindowEvent e) { + public void windowLostFocus(final WindowEvent e) { // TODO Auto-generated method stub } @Override - public void windowMoved(WindowEvent e) { + public void windowMoved(final WindowEvent e) { // TODO Auto-generated method stub } @Override - public void windowRepaint(WindowUpdateEvent e) { + public void windowRepaint(final WindowUpdateEvent e) { // TODO Auto-generated method stub } @Override - public void windowResized(WindowEvent e) { + public void windowResized(final WindowEvent e) { } }); glWindow.addKeyListener(new KeyListener() { @Override - public void keyPressed(KeyEvent arg0) { + public void keyPressed(final KeyEvent arg0) { Keyboard.debugKeyCode = arg0.getKeyCode(); } @Override - public void keyReleased(KeyEvent arg0) { + public void keyReleased(final KeyEvent arg0) { switch (arg0.getKeyCode()) { case KeyEvent.VK_ESCAPE: Keyboard.keyReleased(Key.POWEROFF); @@ -217,72 +215,63 @@ class NEWTWindow implements GLEventListener { Keyboard.keyReleased(Key.debug_GRA); break; case KeyEvent.VK_X: - if (Keyboard.alpha) { + if (Keyboard.alpha) Keyboard.keyReleased(Key.LETTER_X); - } else { + else Keyboard.keyReleased(Key.NONE); - } break; case KeyEvent.VK_P: - if (Keyboard.alpha) { + if (Keyboard.alpha) Keyboard.keyReleased(Key.PI); - } else { + else Keyboard.keyReleased(Key.NONE); - } break; case KeyEvent.VK_B: - if (Keyboard.shift) { + if (Keyboard.shift) Keyboard.keyReleased(Key.BRIGHTNESS_CYCLE_REVERSE); - } else if (!Keyboard.shift && !Keyboard.alpha) { + else if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyReleased(Key.BRIGHTNESS_CYCLE); - } else { + else Keyboard.keyReleased(Key.ZOOM_MODE); - } break; case KeyEvent.VK_ENTER: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyReleased(Key.SIMPLIFY); - } else { + else Keyboard.keyReleased(Key.NONE); - } int row = 2; int col = 1; Keyboard.debugKeysDown[row - 1][col - 1] = false; break; case KeyEvent.VK_1: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyReleased(Key.debug1); - } else { + else Keyboard.keyReleased(Key.NONE); - } break; case KeyEvent.VK_2: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyReleased(Key.debug2); - } else { + else Keyboard.keyReleased(Key.NONE); - } break; case KeyEvent.VK_3: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyReleased(Key.debug3); - } else { + else Keyboard.keyReleased(Key.NONE); - } break; case KeyEvent.VK_4: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyReleased(Key.debug4); - } else { + else Keyboard.keyReleased(Key.NONE); - } break; case KeyEvent.VK_5: - if (!Keyboard.shift && !Keyboard.alpha) { + if (!Keyboard.shift && !Keyboard.alpha) Keyboard.keyReleased(Key.debug5); - } else { + else Keyboard.keyReleased(Key.NONE); - } break; case 0x15: case KeyEvent.VK_SHIFT: @@ -338,7 +327,7 @@ class NEWTWindow implements GLEventListener { glWindow.addMouseListener(new MouseListener() { @Override - public void mouseClicked(MouseEvent e) { + public void mouseClicked(final MouseEvent e) { // List newPoints = new ObjectArrayList<>(); // List changedPoints = new ObjectArrayList<>(); // List oldPoints = touches; @@ -349,7 +338,7 @@ class NEWTWindow implements GLEventListener { // for (int i = 0; i < e.getPointerCount(); i++) { // newPoints.add(Engine.INSTANCE.getHardwareDevice().getInputManager().getTouchDevice().makePoint(is[i], xs[i], ys[i], disp.getWidth(), disp.getHeight(), 5, 5, ps[i], 0)); // } -// +// // changedPoints.add(newPoints.get(0)); // newPoints.remove(0); // touches = newPoints; @@ -358,48 +347,46 @@ class NEWTWindow implements GLEventListener { } @Override - public void mouseEntered(MouseEvent e) { + public void mouseEntered(final MouseEvent e) { // TODO Auto-generated method stub } @Override - public void mouseExited(MouseEvent e) { + public void mouseExited(final MouseEvent e) { // TODO Auto-generated method stub } @Override - public void mousePressed(MouseEvent e) { - List newPoints = new ObjectArrayList<>(); - List changedPoints = new ObjectArrayList<>(); + public void mousePressed(final MouseEvent e) { + final List newPoints = new ObjectArrayList<>(); + final List changedPoints = new ObjectArrayList<>(); @SuppressWarnings("unused") - List oldPoints = touches; - int[] xs = e.getAllX(); - int[] ys = e.getAllY(); - float[] ps = e.getAllPressures(); - short[] is = e.getAllPointerIDs(); - for (int i = 0; i < e.getPointerCount(); i++) { + final List oldPoints = touches; + final int[] xs = e.getAllX(); + final int[] ys = e.getAllY(); + final float[] ps = e.getAllPressures(); + final short[] is = e.getAllPointerIDs(); + for (int i = 0; i < e.getPointerCount(); i++) newPoints.add(Engine.INSTANCE.getHardwareDevice().getInputManager().getTouchDevice().makePoint(is[i], xs[i], ys[i], disp.getWidth(), disp.getHeight(), 5, 5, ps[i], 0)); - } changedPoints.add(newPoints.get(0)); touches = newPoints; Engine.INSTANCE.getHardwareDevice().getInputManager().getTouchDevice().onTouchStart(new TouchStartEvent(changedPoints, touches)); } @Override - public void mouseReleased(MouseEvent e) { - List newPoints = new ObjectArrayList<>(); - List changedPoints = new ObjectArrayList<>(); + public void mouseReleased(final MouseEvent e) { + final List newPoints = new ObjectArrayList<>(); + final List changedPoints = new ObjectArrayList<>(); @SuppressWarnings("unused") - List oldPoints = touches; - int[] xs = e.getAllX(); - int[] ys = e.getAllY(); - float[] ps = e.getAllPressures(); - short[] is = e.getAllPointerIDs(); - for (int i = 0; i < e.getPointerCount(); i++) { + final List oldPoints = touches; + final int[] xs = e.getAllX(); + final int[] ys = e.getAllY(); + final float[] ps = e.getAllPressures(); + final short[] is = e.getAllPointerIDs(); + for (int i = 0; i < e.getPointerCount(); i++) newPoints.add(Engine.INSTANCE.getHardwareDevice().getInputManager().getTouchDevice().makePoint(is[i], xs[i], ys[i], disp.getWidth(), disp.getHeight(), 5, 5, ps[i], 0)); - } changedPoints.add(newPoints.get(0)); newPoints.remove(0); touches = newPoints; @@ -407,32 +394,29 @@ class NEWTWindow implements GLEventListener { } @Override - public void mouseMoved(MouseEvent e) {} + public void mouseMoved(final MouseEvent e) {} private long lastDraggedTime = 0; @Override - public void mouseDragged(MouseEvent e) { - long curTime = System.currentTimeMillis(); + public void mouseDragged(final MouseEvent e) { + final long curTime = System.currentTimeMillis(); if (curTime - lastDraggedTime > 50) { lastDraggedTime = curTime; - List newPoints = new ObjectArrayList<>(); - List changedPoints = new ObjectArrayList<>(); - List oldPoints = touches; - int[] xs = e.getAllX(); - int[] ys = e.getAllY(); - float[] ps = e.getAllPressures(); - short[] is = e.getAllPointerIDs(); - for (int i = 0; i < e.getPointerCount(); i++) { + final List newPoints = new ObjectArrayList<>(); + final List changedPoints = new ObjectArrayList<>(); + final List oldPoints = touches; + final int[] xs = e.getAllX(); + final int[] ys = e.getAllY(); + final float[] ps = e.getAllPressures(); + final short[] is = e.getAllPointerIDs(); + for (int i = 0; i < e.getPointerCount(); i++) newPoints.add(Engine.INSTANCE.getHardwareDevice().getInputManager().getTouchDevice().makePoint(is[i], xs[i], ys[i], disp.getWidth(), disp.getHeight(), 5, 5, ps[i], 0)); - } newPoints.forEach((newp) -> { oldPoints.forEach((oldp) -> { - if (newp.getID() == oldp.getID()) { - if (newp.equals(oldp) == false) { + if (newp.getID() == oldp.getID()) + if (newp.equals(oldp) == false) changedPoints.add(newp); - } - } }); }); touches = newPoints; @@ -441,7 +425,7 @@ class NEWTWindow implements GLEventListener { } @Override - public void mouseWheelMoved(MouseEvent e) { + public void mouseWheelMoved(final MouseEvent e) { } @@ -454,17 +438,16 @@ class NEWTWindow implements GLEventListener { } @Override - public void init(GLAutoDrawable drawable) { + public void init(final GLAutoDrawable drawable) { final GL2ES1 gl = drawable.getGL().getGL2ES1(); onGLContext.onNext(gl); - if (Engine.getPlatform().getSettings().isDebugEnabled()) { + if (Engine.getPlatform().getSettings().isDebugEnabled()) //Vsync gl.setSwapInterval(1); - } else { + else //Vsync gl.setSwapInterval(2); - } //Textures gl.glEnable(GL.GL_TEXTURE_2D); @@ -496,17 +479,17 @@ class NEWTWindow implements GLEventListener { } @Override - public void reshape(GLAutoDrawable glad, int x, int y, int width, int height) { + public void reshape(final GLAutoDrawable glad, final int x, final int y, final int width, final int height) { onRealResize.onNext(new Integer[] { width, height }); } @Override - public void display(GLAutoDrawable glad) { + public void display(final GLAutoDrawable glad) { final GL2ES1 gl = glad.getGL().getGL2ES1(); JOGLRenderer.gl = gl; onGLContext.onNext(gl); - boolean linear = (windowZoom % ((int) windowZoom)) != 0f; + final boolean linear = windowZoom % (int) windowZoom != 0f; if (refreshViewport) { System.err.println("[[[REFVP"); refreshViewport = false; @@ -552,18 +535,16 @@ class NEWTWindow implements GLEventListener { void setSize(final int width, final int height) { int zoom = (int) windowZoom; - if (zoom == 0) { + if (zoom == 0) zoom = onZoom.getLastValue().intValue(); - } - if (zoom == 0) { + if (zoom == 0) zoom = 1; - } window.setSize(width * zoom, height * zoom); onRealResize.onNext(new Integer[] { width * zoom, height * zoom }); } @Override - public void dispose(GLAutoDrawable drawable) { + public void dispose(final GLAutoDrawable drawable) { System.out.println("cleanup"); // final GL2ES1 gl = drawable.getGL().getGL2ES1(); System.exit(0); diff --git a/hardware/src/main/java/cz/adamh/utils/NativeUtils.java b/hardware/src/main/java/cz/adamh/utils/NativeUtils.java index 9093679e..a66a0148 100644 --- a/hardware/src/main/java/cz/adamh/utils/NativeUtils.java +++ b/hardware/src/main/java/cz/adamh/utils/NativeUtils.java @@ -38,7 +38,7 @@ import java.nio.file.StandardCopyOption; * the * JAR archive. These libraries usualy contain implementation of some methods in * native code (using JNI - Java Native Interface). - * + * * @see http://adamheinrich.com/blog/2012/how-to-load-native-jni-library-from-jar * @see https://github.com/adamheinrich/native-utils * @@ -63,13 +63,13 @@ public class NativeUtils { /** * Loads library from current JAR archive - * + * * The file from JAR is copied into system temporary directory and then * loaded. The temporary file is deleted after * exiting. * Method uses String as filename because the pathname is "abstract", not * system-dependent. - * + * * @param path * The path of file inside JAR as absolute path (beginning with * '/'), e.g. /package/File.ext @@ -85,28 +85,26 @@ public class NativeUtils { * @throws FileNotFoundException * If the file could not be found inside the JAR. */ - public static void loadLibraryFromJar(String path) throws IOException { + public static void loadLibraryFromJar(final String path) throws IOException { - if (!path.startsWith("/")) { + if (!path.startsWith("/")) throw new IllegalArgumentException("The path has to be absolute (start with '/')."); - } // Obtain filename from path final String[] parts = path.split("/"); - final String filename = (parts.length > 1) ? parts[parts.length - 1] : null; + final String filename = parts.length > 1 ? parts[parts.length - 1] : null; // Check if the filename is okay - if (filename == null || filename.length() < MIN_PREFIX_LENGTH) { + if (filename == null || filename.length() < NativeUtils.MIN_PREFIX_LENGTH) throw new IllegalArgumentException("The filename has to be at least 3 characters long."); - } // Prepare temporary file - if (temporaryDir == null) { - temporaryDir = createTempDirectory("nativeutils"); - temporaryDir.deleteOnExit(); + if (NativeUtils.temporaryDir == null) { + NativeUtils.temporaryDir = NativeUtils.createTempDirectory("nativeutils"); + NativeUtils.temporaryDir.deleteOnExit(); } - final File temp = new File(temporaryDir, filename); + final File temp = new File(NativeUtils.temporaryDir, filename); try (InputStream is = NativeUtils.class.getResourceAsStream(path)) { Files.copy(is, temp.toPath(), StandardCopyOption.REPLACE_EXISTING); @@ -121,34 +119,31 @@ public class NativeUtils { try { System.load(temp.getAbsolutePath()); } finally { - if (isPosixCompliant()) { + if (NativeUtils.isPosixCompliant()) // Assume POSIX compliant file system, can be deleted after loading temp.delete(); - } else { + else // Assume non-POSIX, and don't delete until last file descriptor closed temp.deleteOnExit(); - } } } private static boolean isPosixCompliant() { try { - if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) { + if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) return true; - } return false; } catch (FileSystemNotFoundException | ProviderNotFoundException | SecurityException e) { return false; } } - private static File createTempDirectory(String prefix) throws IOException { + private static File createTempDirectory(final String prefix) throws IOException { final String tempDir = System.getProperty("java.io.tmpdir"); final File generatedDir = new File(tempDir, prefix + System.nanoTime()); - if (!generatedDir.mkdir()) { + if (!generatedDir.mkdir()) throw new IOException("Failed to create temp directory " + generatedDir.getName()); - } return generatedDir; } diff --git a/hardware/src/main/java/it/cavallium/warppi/MmapByteBuffer.java b/hardware/src/main/java/it/cavallium/warppi/MmapByteBuffer.java index 784dc240..c6ef8256 100644 --- a/hardware/src/main/java/it/cavallium/warppi/MmapByteBuffer.java +++ b/hardware/src/main/java/it/cavallium/warppi/MmapByteBuffer.java @@ -8,7 +8,7 @@ public class MmapByteBuffer { private final int length; private final ByteBuffer buffer; - public MmapByteBuffer(int fd, int address, int length, ByteBuffer buffer) { + public MmapByteBuffer(final int fd, final int address, final int length, final ByteBuffer buffer) { this.fd = fd; this.address = address; this.length = length; diff --git a/hardware/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/framebuffer/FBEngine.java b/hardware/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/framebuffer/FBEngine.java index 74aba326..aab46c2d 100644 --- a/hardware/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/framebuffer/FBEngine.java +++ b/hardware/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/framebuffer/FBEngine.java @@ -25,7 +25,7 @@ public class FBEngine implements GraphicEngine { private static final int FB_DISPLAY_BPP = 32; private static final int WIDTH = 480; private static final int HEIGHT = 320; - private static final int[] SIZE = new int[] { WIDTH, HEIGHT }; + private static final int[] SIZE = new int[] { FBEngine.WIDTH, FBEngine.HEIGHT }; private BehaviorSubject onResize; private final TestJNI jni = new TestJNI(); public FBRenderer r; @@ -37,7 +37,7 @@ public class FBEngine implements GraphicEngine { @Override public int[] getSize() { - return SIZE; + return FBEngine.SIZE; } @Override @@ -46,17 +46,17 @@ public class FBEngine implements GraphicEngine { } @Override - public void setTitle(String title) {} + public void setTitle(final String title) {} @Override - public void setResizable(boolean r) {} + public void setResizable(final boolean r) {} @Override - public void setDisplayMode(int ww, int wh) {} + public void setDisplayMode(final int ww, final int wh) {} @Override - public void create(Runnable onInitialized) { - onResize = BehaviorSubject.create(new Integer[] { SIZE[0], SIZE[1] }); + public void create(final Runnable onInitialized) { + onResize = BehaviorSubject.create(new Integer[] { FBEngine.SIZE[0], FBEngine.SIZE[1] }); realFb = jni.retrieveBuffer(); final long fbLen = realFb.getLength(); fb = (MappedByteBuffer) ByteBuffer.allocateDirect((int) fbLen); @@ -64,9 +64,8 @@ public class FBEngine implements GraphicEngine { r = new FBRenderer(this, fb); initialized = true; - if (onInitialized != null) { + if (onInitialized != null) onInitialized.run(); - } } @Override @@ -76,12 +75,12 @@ public class FBEngine implements GraphicEngine { @Override public int getWidth() { - return WIDTH; + return FBEngine.WIDTH; } @Override public int getHeight() { - return HEIGHT; + return FBEngine.HEIGHT; } @Override @@ -94,7 +93,7 @@ public class FBEngine implements GraphicEngine { } @Override - public void start(RenderingLoop d) { + public void start(final RenderingLoop d) { final Thread th = new Thread(() -> { try { double extratime = 0; @@ -109,9 +108,8 @@ public class FBEngine implements GraphicEngine { if (extraTimeInt + deltaInt < 50) { Thread.sleep(50 - (extraTimeInt + deltaInt)); extratime = 0; - } else { + } else extratime += delta - 50d; - } } } catch (final InterruptedException e) { e.printStackTrace(); @@ -133,12 +131,10 @@ public class FBEngine implements GraphicEngine { _________________TMP++; realFb.getBuffer().clear(); realFb.getBuffer().put(fb); - for (int i = 0; i < fb.capacity() / 2; i++) { + for (int i = 0; i < fb.capacity() / 2; i++) realFb.getBuffer().put(i, (byte) (_________________TMP < 50 ? 0xFF : 0xF0)); - } - for (int i = fb.capacity() / 2; i < fb.capacity(); i++) { - realFb.getBuffer().put(i, (byte) (0x18)); - } + for (int i = fb.capacity() / 2; i < fb.capacity(); i++) + realFb.getBuffer().put(i, (byte) 0x18); } @Override @@ -147,17 +143,17 @@ public class FBEngine implements GraphicEngine { } @Override - public FBFont loadFont(String fontName) throws IOException { + public FBFont loadFont(final String fontName) throws IOException { return new FBFont(fontName); } @Override - public FBFont loadFont(String path, String fontName) throws IOException { + public FBFont loadFont(final String path, final String fontName) throws IOException { return new FBFont(path, fontName); } @Override - public FBSkin loadSkin(String file) throws IOException { + public FBSkin loadSkin(final String file) throws IOException { return new FBSkin(file); } @@ -170,12 +166,10 @@ public class FBEngine implements GraphicEngine { @Override public boolean isSupported() { - if (StaticVars.startupArguments.isEngineForced() && StaticVars.startupArguments.isFrameBufferEngineForced() == false) { + if (StaticVars.startupArguments.isEngineForced() && StaticVars.startupArguments.isFrameBufferEngineForced() == false) return false; - } - if (StaticVars.startupArguments.isHeadlessEngineForced()) { + if (StaticVars.startupArguments.isHeadlessEngineForced()) return false; - } /* File fbFile = new File("/dev/fb1"); try { diff --git a/hardware/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/framebuffer/FBFont.java b/hardware/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/framebuffer/FBFont.java index 637d97e9..115fad26 100644 --- a/hardware/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/framebuffer/FBFont.java +++ b/hardware/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/framebuffer/FBFont.java @@ -7,19 +7,19 @@ import it.cavallium.warppi.gui.graphicengine.impl.common.RFTFont; public class FBFont extends RFTFont { - public FBFont(String fontName) throws IOException { + public FBFont(final String fontName) throws IOException { super(fontName); } - - public FBFont(String path, String fontName) throws IOException { + + public FBFont(final String path, final String fontName) throws IOException { super(path, fontName); } @Override - public void use(GraphicEngine d) { - FBEngine dfb = (FBEngine) d; + public void use(final GraphicEngine d) { + @SuppressWarnings("unused") + final FBEngine dfb = (FBEngine) d; // TODO: implement } - } diff --git a/hardware/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/framebuffer/FBRenderer.java b/hardware/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/framebuffer/FBRenderer.java index 2e61d4ab..e42e343e 100644 --- a/hardware/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/framebuffer/FBRenderer.java +++ b/hardware/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/framebuffer/FBRenderer.java @@ -7,46 +7,46 @@ import it.cavallium.warppi.gui.graphicengine.Renderer; public class FBRenderer implements Renderer { - public FBRenderer(FBEngine fbEngine, MappedByteBuffer fb) {} + public FBRenderer(final FBEngine fbEngine, final MappedByteBuffer fb) {} @Override - public void glColor3i(int r, int gg, int b) { + public void glColor3i(final int r, final int gg, final int b) { // TODO Auto-generated method stub } @Override - public void glColor(int c) { + public void glColor(final int c) { // TODO Auto-generated method stub } @Override - public void glColor4i(int red, int green, int blue, int alpha) { + public void glColor4i(final int red, final int green, final int blue, final int alpha) { // TODO Auto-generated method stub } @Override - public void glColor3f(float red, float green, float blue) { + public void glColor3f(final float red, final float green, final float blue) { // TODO Auto-generated method stub } @Override - public void glColor4f(float red, float green, float blue, float alpha) { + public void glColor4f(final float red, final float green, final float blue, final float alpha) { // TODO Auto-generated method stub } @Override - public void glClearColor4i(int red, int green, int blue, int alpha) { + public void glClearColor4i(final int red, final int green, final int blue, final int alpha) { // TODO Auto-generated method stub } @Override - public void glClearColor4f(float red, float green, float blue, float alpha) { + public void glClearColor4f(final float red, final float green, final float blue, final float alpha) { // TODO Auto-generated method stub } @@ -58,68 +58,68 @@ public class FBRenderer implements Renderer { } @Override - public void glClearColor(int c) { + public void glClearColor(final int c) { // TODO Auto-generated method stub } @Override - public void glClear(int screenWidth, int screenHeight) { + public void glClear(final int screenWidth, final int screenHeight) { // TODO Auto-generated method stub } @Override - public void glDrawLine(float x0, float y0, float x1, float y1) { + public void glDrawLine(final float x0, final float y0, final float x1, final float y1) { // TODO Auto-generated method stub } @Override - public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth, - float uvHeight) { + public void glFillRect(final float x, final float y, final float width, final float height, final float uvX, + final float uvY, final float uvWidth, final float uvHeight) { // TODO Auto-generated method stub } @Override - public void glFillColor(float x, float y, float width, float height) { + public void glFillColor(final float x, final float y, final float width, final float height) { // TODO Auto-generated method stub } @Override - public void glDrawCharLeft(int x, int y, char ch) { + public void glDrawCharLeft(final int x, final int y, final char ch) { // TODO Auto-generated method stub } @Override - public void glDrawCharCenter(int x, int y, char ch) { + public void glDrawCharCenter(final int x, final int y, final char ch) { // TODO Auto-generated method stub } @Override - public void glDrawCharRight(int x, int y, char ch) { + public void glDrawCharRight(final int x, final int y, final char ch) { // TODO Auto-generated method stub } @Override - public void glDrawStringLeft(float x, float y, String text) { + public void glDrawStringLeft(final float x, final float y, final String text) { // TODO Auto-generated method stub } @Override - public void glDrawStringCenter(float x, float y, String text) { + public void glDrawStringCenter(final float x, final float y, final String text) { // TODO Auto-generated method stub } @Override - public void glDrawStringRight(float x, float y, String text) { + public void glDrawStringRight(final float x, final float y, final String text) { // TODO Auto-generated method stub } diff --git a/hardware/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/framebuffer/FBSkin.java b/hardware/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/framebuffer/FBSkin.java index 170d2c16..4ad36356 100644 --- a/hardware/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/framebuffer/FBSkin.java +++ b/hardware/src/main/java/it/cavallium/warppi/gui/graphicengine/impl/framebuffer/FBSkin.java @@ -7,13 +7,14 @@ import it.cavallium.warppi.gui.graphicengine.impl.common.PngSkin; public class FBSkin extends PngSkin { - public FBSkin(String file) throws IOException { + public FBSkin(final String file) throws IOException { super(file); } @Override - public void use(GraphicEngine d) { - FBEngine dfb = (FBEngine) d; + public void use(final GraphicEngine d) { + @SuppressWarnings("unused") + final FBEngine dfb = (FBEngine) d; // TODO: implement } diff --git a/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareBoot.java b/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareBoot.java index f339fd42..5a4e4cd1 100644 --- a/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareBoot.java +++ b/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareBoot.java @@ -4,7 +4,7 @@ import it.cavallium.warppi.boot.Boot; public class HardwareBoot { - public static void main(String[] args) throws Exception { + public static void main(final String[] args) throws Exception { Boot.boot(new HardwarePlatform(), args); } diff --git a/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareConsoleUtils.java b/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareConsoleUtils.java index daacdfe0..c915b771 100644 --- a/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareConsoleUtils.java +++ b/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareConsoleUtils.java @@ -13,74 +13,74 @@ public class HardwareConsoleUtils implements it.cavallium.warppi.Platform.Consol public HardwareConsoleUtils() { os = new AdvancedOutputStream() { - private void print(PrintStream stream, String str) { + private void print(final PrintStream stream, final String str) { stream.print(fixString(str)); } - private void println(PrintStream stream, String str) { + private void println(final PrintStream stream, final String str) { stream.println(fixString(str)); } - private void println(PrintStream stream) { + private void println(final PrintStream stream) { stream.println(); } - private String fixString(String str) { + private String fixString(final String str) { return str.replace("" + MathematicalSymbols.NTH_ROOT, "root").replace("" + MathematicalSymbols.SQUARE_ROOT, "sqrt").replace("" + MathematicalSymbols.POWER, "powerOf").replace("" + MathematicalSymbols.POWER_OF_TWO, "powerOfTwo").replace("" + MathematicalSymbols.SINE, "sine").replace("" + MathematicalSymbols.COSINE, "cosine").replace("" + MathematicalSymbols.TANGENT, "tangent").replace("" + MathematicalSymbols.ARC_SINE, "asin").replace("" + MathematicalSymbols.ARC_COSINE, "acos").replace("" + MathematicalSymbols.ARC_TANGENT, "atan").replace("" + MathematicalSymbols.UNDEFINED, "undefined").replace("" + MathematicalSymbols.PI, "PI").replace("" + MathematicalSymbols.EULER_NUMBER, "EULER_NUMBER").replace("" + MathematicalSymbols.X, "X").replace("" + MathematicalSymbols.Y, "Y"); } - public void println(Object str) { + @Override + public void println(final Object str) { println(0, str); } - public void println(int level) { - if (StaticVars.outputLevel >= level) { - if (StaticVars.outputLevel == 0) { + @Override + public void println(final int level) { + if (StaticVars.outputLevel >= level) + if (StaticVars.outputLevel == 0) println(System.out); - } else { + else println(System.out); - } - } } - public void println(int level, Object str) { + @Override + public void println(final int level, final Object str) { if (StaticVars.outputLevel >= level) { final String time = getTimeString(); - if (StaticVars.outputLevel == 0) { + if (StaticVars.outputLevel == 0) println(System.out, "[" + time + "] " + str); - } else { + else println(System.out, "[" + time + "] " + str); - } } } - public void print(int level, String str) { - if (StaticVars.outputLevel >= level) { - if (StaticVars.outputLevel == 0) { + @Override + public void print(final int level, final String str) { + if (StaticVars.outputLevel >= level) + if (StaticVars.outputLevel == 0) print(System.out, str); - } else { + else print(System.out, str); - } - } } - public void println(int level, String prefix, String str) { + @Override + public void println(final int level, final String prefix, final String str) { if (StaticVars.outputLevel >= level) { final String time = getTimeString(); - if (StaticVars.outputLevel == 0) { + if (StaticVars.outputLevel == 0) println(System.out, "[" + time + "][" + prefix + "] " + str); - } else { + else println(System.out, "[" + time + "][" + prefix + "] " + str); - } } } - public void println(int level, String... parts) { + @Override + public void println(final int level, final String... parts) { if (StaticVars.outputLevel >= level) { final String time = getTimeString(); - StringBuilder output = new StringBuilder(); - for (int i = 0; i < parts.length; i++) { + final StringBuilder output = new StringBuilder(); + for (int i = 0; i < parts.length; i++) if (i + 1 == parts.length) { output.append(' '); output.append(parts[i]); @@ -89,15 +89,13 @@ public class HardwareConsoleUtils implements it.cavallium.warppi.Platform.Consol output.append(parts[i]); output.append(']'); } - } output.insert(0, '['); output.insert(1, time); output.insert(time.length() + 1, ']'); - if (StaticVars.outputLevel == 0) { + if (StaticVars.outputLevel == 0) println(System.out, output.toString()); - } else { + else println(System.out, output.toString()); - } } } @@ -106,7 +104,7 @@ public class HardwareConsoleUtils implements it.cavallium.warppi.Platform.Consol } }; } - + @Override public AdvancedOutputStream out() { return os; diff --git a/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareGpio.java b/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareGpio.java index 0e66268a..3443f1ee 100644 --- a/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareGpio.java +++ b/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareGpio.java @@ -40,33 +40,33 @@ public class HardwareGpio implements it.cavallium.warppi.Platform.Gpio { } @Override - public void pinMode(int i, int type) { + public void pinMode(final int i, final int type) { com.pi4j.wiringpi.Gpio.pinMode(i, type); - + } @Override - public void digitalWrite(int pin, int val) { + public void digitalWrite(final int pin, final int val) { com.pi4j.wiringpi.Gpio.digitalWrite(pin, val); } @Override - public void digitalWrite(int pin, boolean val) { + public void digitalWrite(final int pin, final boolean val) { com.pi4j.wiringpi.Gpio.digitalWrite(pin, val); } @Override - public void pwmWrite(int pin, int val) { + public void pwmWrite(final int pin, final int val) { com.pi4j.wiringpi.Gpio.pwmWrite(pin, val); } @Override - public void delayMicroseconds(int t) { + public void delayMicroseconds(final int t) { com.pi4j.wiringpi.Gpio.delayMicroseconds(t); } @Override - public int digitalRead(int pin) { + public int digitalRead(final int pin) { return com.pi4j.wiringpi.Gpio.digitalRead(pin); } diff --git a/hardware/src/main/java/it/cavallium/warppi/hardware/HardwarePlatform.java b/hardware/src/main/java/it/cavallium/warppi/hardware/HardwarePlatform.java index 1a0923ea..e1ab9c94 100644 --- a/hardware/src/main/java/it/cavallium/warppi/hardware/HardwarePlatform.java +++ b/hardware/src/main/java/it/cavallium/warppi/hardware/HardwarePlatform.java @@ -37,7 +37,7 @@ public class HardwarePlatform implements Platform { el.put("framebuffer engine", new FBEngine()); settings = new HardwareSettings(); } - + @Override public ConsoleUtils getConsoleUtils() { return cu; @@ -64,22 +64,22 @@ public class HardwarePlatform implements Platform { } @Override - public void setThreadName(Thread t, String name) { + public void setThreadName(final Thread t, final String name) { t.setName(name); } @Override - public void setThreadDaemon(Thread t) { + public void setThreadDaemon(final Thread t) { t.setDaemon(true); } @Override - public void setThreadDaemon(Thread t, boolean value) { + public void setThreadDaemon(final Thread t, final boolean value) { t.setDaemon(value); } @Override - public void exit(int value) { + public void exit(final int value) { System.exit(value); } @@ -99,13 +99,12 @@ public class HardwarePlatform implements Platform { } @Override - public void alphaChanged(boolean val) { - + public void alphaChanged(final boolean val) { + } @Override - public void shiftChanged(boolean val) { - } + public void shiftChanged(final boolean val) {} @Override public Semaphore newSemaphore() { @@ -113,12 +112,12 @@ public class HardwarePlatform implements Platform { } @Override - public Semaphore newSemaphore(int i) { + public Semaphore newSemaphore(final int i) { return new HardwareSemaphore(i); } @Override - public URLClassLoader newURLClassLoader(URL[] urls) { + public URLClassLoader newURLClassLoader(final URL[] urls) { return new HardwareURLClassLoader(urls); } @@ -128,17 +127,17 @@ public class HardwarePlatform implements Platform { } @Override - public GraphicEngine getEngine(String string) throws NullPointerException { + public GraphicEngine getEngine(final String string) throws NullPointerException { return el.get(string); } @Override - public void throwNewExceptionInInitializerError(String text) { + public void throwNewExceptionInInitializerError(final String text) { throw new ExceptionInInitializerError(); } @Override - public String[] stacktraceToString(Error e) { + public String[] stacktraceToString(final Error e) { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); @@ -147,11 +146,11 @@ public class HardwarePlatform implements Platform { @Override public void loadPlatformRules() { - + } @Override - public void zip(String targetPath, String destinationFilePath, String password) { + public void zip(final String targetPath, final String destinationFilePath, final String password) { try { final ZipParameters parameters = new ZipParameters(); parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); @@ -167,11 +166,10 @@ public class HardwarePlatform implements Platform { final ZipFile zipFile = new ZipFile(destinationFilePath); final File targetFile = new File(targetPath); - if (targetFile.isFile()) { + if (targetFile.isFile()) zipFile.addFile(targetFile, parameters); - } else if (targetFile.isDirectory()) { + else if (targetFile.isDirectory()) zipFile.addFolder(targetFile, parameters); - } } catch (final Exception e) { e.printStackTrace(); @@ -179,12 +177,11 @@ public class HardwarePlatform implements Platform { } @Override - public void unzip(String targetZipFilePath, String destinationFolderPath, String password) { + public void unzip(final String targetZipFilePath, final String destinationFolderPath, final String password) { try { final ZipFile zipFile = new ZipFile(targetZipFilePath); - if (zipFile.isEncrypted()) { + if (zipFile.isEncrypted()) zipFile.setPassword(password); - } zipFile.extractAll(destinationFolderPath); } catch (final Exception e) { @@ -193,7 +190,7 @@ public class HardwarePlatform implements Platform { } @Override - public boolean compile(String[] command, PrintWriter printWriter, PrintWriter errors) { + public boolean compile(final String[] command, final PrintWriter printWriter, final PrintWriter errors) { return org.eclipse.jdt.internal.compiler.batch.Main.compile(command, printWriter, errors, null); } @@ -216,7 +213,7 @@ public class HardwarePlatform implements Platform { } catch (IOException readException) { return false; } - + } else { return false; } diff --git a/hardware/src/main/java/it/cavallium/warppi/hardware/HardwarePngReader.java b/hardware/src/main/java/it/cavallium/warppi/hardware/HardwarePngReader.java index 75209d03..30043b0b 100644 --- a/hardware/src/main/java/it/cavallium/warppi/hardware/HardwarePngReader.java +++ b/hardware/src/main/java/it/cavallium/warppi/hardware/HardwarePngReader.java @@ -7,9 +7,9 @@ import it.cavallium.warppi.Platform.PngUtils.PngReader; public class HardwarePngReader implements PngReader { - private ar.com.hjg.pngj.PngReader r; - - public HardwarePngReader(InputStream resourceStream) { + private final ar.com.hjg.pngj.PngReader r; + + public HardwarePngReader(final InputStream resourceStream) { r = new ar.com.hjg.pngj.PngReader(resourceStream); } @@ -23,25 +23,24 @@ public class HardwarePngReader implements PngReader { ImageLineInt lint; while (r.hasMoreRows()) { lint = (ImageLineInt) r.readRow(); - int[] scanLine = lint.getScanline(); + final int[] scanLine = lint.getScanline(); for (int i = 0; i < width; i++) { - int offset = i * channels; + final int offset = i * channels; // Adjust the following code depending on your source image. // I need the to set the alpha channel to 0xFF000000 since my destination image // is TRANSLUCENT : BufferedImage bi = CONFIG.createCompatibleImage( width, height, Transparency.TRANSLUCENT ); // my source was 3 channels RGB without transparency int nextPixel; - if (channels == 4) { - nextPixel = (scanLine[offset] << 16) | (scanLine[offset + 1] << 8) | (scanLine[offset + 2]) | (scanLine[offset + 3] << 24); - } else if (channels == 3) { - nextPixel = (scanLine[offset] << 16) | (scanLine[offset + 1] << 8) | (scanLine[offset + 2]) | (0xFF << 24); - } else if (channels == 2) { - nextPixel = (scanLine[offset] << 16) | (scanLine[offset + 1] << 8) | 0xFF | (0xFF << 24); - } else { - nextPixel = (scanLine[offset] << 16) | (scanLine[offset] << 8) | scanLine[offset] | (0xFF << 24); - } + if (channels == 4) + nextPixel = scanLine[offset] << 16 | scanLine[offset + 1] << 8 | scanLine[offset + 2] | scanLine[offset + 3] << 24; + else if (channels == 3) + nextPixel = scanLine[offset] << 16 | scanLine[offset + 1] << 8 | scanLine[offset + 2] | 0xFF << 24; + else if (channels == 2) + nextPixel = scanLine[offset] << 16 | scanLine[offset + 1] << 8 | 0xFF | 0xFF << 24; + else + nextPixel = scanLine[offset] << 16 | scanLine[offset] << 8 | scanLine[offset] | 0xFF << 24; // I'm placing the pixels on a memory mapped file pixels[pi] = nextPixel; @@ -55,7 +54,7 @@ public class HardwarePngReader implements PngReader { @Override public int[] getSize() { - return new int[] {r.imgInfo.cols, r.imgInfo.rows}; + return new int[] { r.imgInfo.cols, r.imgInfo.rows }; } } diff --git a/hardware/src/main/java/it/cavallium/warppi/hardware/HardwarePngUtils.java b/hardware/src/main/java/it/cavallium/warppi/hardware/HardwarePngUtils.java index b5dc341e..c5943f17 100644 --- a/hardware/src/main/java/it/cavallium/warppi/hardware/HardwarePngUtils.java +++ b/hardware/src/main/java/it/cavallium/warppi/hardware/HardwarePngUtils.java @@ -7,7 +7,7 @@ import it.cavallium.warppi.Platform.PngUtils; public class HardwarePngUtils implements PngUtils { @Override - public PngReader load(InputStream resourceStream) { + public PngReader load(final InputStream resourceStream) { return new HardwarePngReader(resourceStream); } diff --git a/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareSemaphore.java b/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareSemaphore.java index 209d7fd3..17cbbb50 100644 --- a/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareSemaphore.java +++ b/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareSemaphore.java @@ -6,11 +6,11 @@ public class HardwareSemaphore extends Semaphore implements it.cavallium.warppi. private static final long serialVersionUID = -2362314723921013871L; - public HardwareSemaphore(int arg0) { + public HardwareSemaphore(final int arg0) { super(arg0); } - public HardwareSemaphore(int permits, boolean fair) { + public HardwareSemaphore(final int permits, final boolean fair) { super(permits, fair); } } diff --git a/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareSettings.java b/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareSettings.java index 7faffc3e..0bf94ae9 100644 --- a/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareSettings.java +++ b/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareSettings.java @@ -7,16 +7,16 @@ public class HardwareSettings implements Settings { private boolean debug; public HardwareSettings() { - this.debug = true; + debug = true; } - + @Override public boolean isDebugEnabled() { return debug; } @Override - public void setDebugEnabled(boolean debug) { + public void setDebugEnabled(final boolean debug) { this.debug = debug; } diff --git a/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareStorageUtils.java b/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareStorageUtils.java index 724729c4..5147e039 100644 --- a/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareStorageUtils.java +++ b/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareStorageUtils.java @@ -30,39 +30,41 @@ import it.cavallium.warppi.Platform.StorageUtils; import it.cavallium.warppi.util.ClassUtils; public class HardwareStorageUtils implements StorageUtils { - public boolean exists(File f) { + @Override + public boolean exists(final File f) { return f.exists(); } - public File get(String path) { + @Override + public File get(final String path) { return Paths.get(path).toFile(); } - public File get(String... path) { - if (path.length <= 1) { + @Override + public File get(final String... path) { + if (path.length <= 1) return Paths.get(path[0]).toFile(); - } else { + else return Paths.get(path[0], Arrays.copyOfRange(path, 1, path.length)).toFile(); - } } - private Map resourcesCache = new HashMap(); + private final Map resourcesCache = new HashMap<>(); + @Override @Deprecated() - public File getResource(String string) throws IOException, URISyntaxException { + public File getResource(final String string) throws IOException, URISyntaxException { final URL res = ClassUtils.classLoader.getResource(string); final boolean isResource = res != null; - if (isResource) { + if (isResource) try { final URI uri = res.toURI(); if (res.getProtocol().equalsIgnoreCase("jar")) { if (resourcesCache.containsKey(string)) { File f; - if ((f = resourcesCache.get(string)).exists()) { + if ((f = resourcesCache.get(string)).exists()) return f; - } else { + else resourcesCache.remove(string); - } } try { FileSystems.newFileSystem(uri, Collections.emptyMap()); @@ -71,7 +73,7 @@ public class HardwareStorageUtils implements StorageUtils { } final Path myFolderPath = Paths.get(uri); - InputStream is = Files.newInputStream(myFolderPath); + final InputStream is = Files.newInputStream(myFolderPath); final File tempFile = File.createTempFile("picalcresource-", ""); tempFile.deleteOnExit(); try (FileOutputStream out = new FileOutputStream(tempFile)) { @@ -80,21 +82,20 @@ public class HardwareStorageUtils implements StorageUtils { resourcesCache.put(string, tempFile); return tempFile; - } else { + } else return Paths.get(uri).toFile(); - } } catch (final java.lang.IllegalArgumentException e) { throw e; } - } else { + else return Paths.get(string.substring(1)).toFile(); - } } + @Override public InputStream getResourceStream(String string) throws IOException, URISyntaxException { final URL res = ClassUtils.classLoader.getResource(string); final boolean isResource = res != null; - if (isResource) { + if (isResource) try { final URI uri = res.toURI(); if (res.getProtocol().equalsIgnoreCase("jar")) { @@ -105,63 +106,69 @@ public class HardwareStorageUtils implements StorageUtils { } final Path myFolderPath = Paths.get(uri); return Files.newInputStream(myFolderPath); - } else { + } else return Files.newInputStream(Paths.get(uri)); - } } catch (final java.lang.IllegalArgumentException e) { throw e; } - } else { + else { if (string.length() > 0) { - char ch = string.charAt(0); - if (ch == '/' || ch == File.separatorChar) { + final char ch = string.charAt(0); + if (ch == '/' || ch == File.separatorChar) string = string.substring(1); - } } return Files.newInputStream(Paths.get(string)); } } - public List readAllLines(File file) throws IOException { + @Override + public List readAllLines(final File file) throws IOException { return Files.readAllLines(file.toPath()); } - public String read(InputStream input) throws IOException { + @Override + public String read(final InputStream input) throws IOException { try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) { return buffer.lines().collect(Collectors.joining("\n")); } } - public List walk(File dir) throws IOException { - List out = new ArrayList<>(); + @Override + public List walk(final File dir) throws IOException { + final List out = new ArrayList<>(); try (Stream paths = Files.walk(dir.toPath())) { - paths.filter(Files::isRegularFile).forEach((Path p) -> { + paths.filter(Files::isRegularFile).forEach((final Path p) -> { out.add(p.toFile()); }); } return out; } - public File relativize(File rulesPath, File f) { + @Override + public File relativize(final File rulesPath, final File f) { return rulesPath.toPath().relativize(f.toPath()).toFile(); } - public File resolve(File file, String string) { + @Override + public File resolve(final File file, final String string) { return file.toPath().resolve(string).toFile(); } - public File getParent(File f) { + @Override + public File getParent(final File f) { return f.toPath().getParent().toFile(); } - public void createDirectories(File dir) throws IOException { + @Override + public void createDirectories(final File dir) throws IOException { Files.createDirectories(dir.toPath()); } - public void write(File f, byte[] bytes, int... options) throws IOException { - StandardOpenOption[] noptions = new StandardOpenOption[options.length]; + @Override + public void write(final File f, final byte[] bytes, final int... options) throws IOException { + final StandardOpenOption[] noptions = new StandardOpenOption[options.length]; int i = 0; - for (int opt : options) { + for (final int opt : options) { switch (opt) { case StorageUtils.OpenOptionCreate: { noptions[i] = StandardOpenOption.CREATE; @@ -180,7 +187,8 @@ public class HardwareStorageUtils implements StorageUtils { Files.write(f.toPath(), bytes, noptions); } - public List readAllLines(InputStream input) throws IOException { + @Override + public List readAllLines(final InputStream input) throws IOException { try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) { return buffer.lines().collect(Collectors.toList()); } diff --git a/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareURLClassLoader.java b/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareURLClassLoader.java index 81f04629..ff5a98cb 100644 --- a/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareURLClassLoader.java +++ b/hardware/src/main/java/it/cavallium/warppi/hardware/HardwareURLClassLoader.java @@ -6,7 +6,7 @@ import it.cavallium.warppi.Platform.URLClassLoader; public class HardwareURLClassLoader extends java.net.URLClassLoader implements URLClassLoader { - public HardwareURLClassLoader(URL[] urls) { + public HardwareURLClassLoader(final URL[] urls) { super(urls); } diff --git a/rules/src/main/java/rules/ExpandRule1.java b/rules/src/main/java/rules/ExpandRule1.java index 8c39bc5a..4e1bd21c 100644 --- a/rules/src/main/java/rules/ExpandRule1.java +++ b/rules/src/main/java/rules/ExpandRule1.java @@ -4,8 +4,6 @@ SETTINGS: (please don't move this part) PATH=ExpandRule1 */ - - import it.cavallium.warppi.math.Function; import it.cavallium.warppi.math.FunctionOperator; import it.cavallium.warppi.math.MathContext; @@ -22,7 +20,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; * Expand rule * -(+a+b) = -a-b * -(+a-b) = -a+b - * + * * @author Andrea Cavalli * */ @@ -45,83 +43,78 @@ public class ExpandRule1 implements Rule { - An ObjectArrayList if it did something */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Multiplication) { - Multiplication fnc = (Multiplication) f; + final Multiplication fnc = (Multiplication) f; if (fnc.getParameter1().equals(new Number(fnc.getMathContext(), -1))) { - Function expr = fnc.getParameter2(); - if (expr instanceof Sum) { + final Function expr = fnc.getParameter2(); + if (expr instanceof Sum) isExecutable = true; - } else if (expr instanceof Subtraction) { + else if (expr instanceof Subtraction) isExecutable = true; - } else if (expr instanceof SumSubtraction) { + else if (expr instanceof SumSubtraction) isExecutable = true; - } } } else if (f instanceof Subtraction || f instanceof SumSubtraction) { - FunctionOperator fnc = (FunctionOperator) f; - Function expr = fnc.getParameter2(); - if (expr instanceof Sum) { + final FunctionOperator fnc = (FunctionOperator) f; + final Function expr = fnc.getParameter2(); + if (expr instanceof Sum) isExecutable = true; - } else if (expr instanceof Subtraction) { + else if (expr instanceof Subtraction) isExecutable = true; - } else if (expr instanceof SumSubtraction) { + else if (expr instanceof SumSubtraction) isExecutable = true; - } } if (isExecutable) { - ObjectArrayList result = new ObjectArrayList<>(); - MathContext root = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); + final MathContext root = f.getMathContext(); Function expr = null; int fromSubtraction = 0; FunctionOperator subtraction = null; - if (f instanceof Multiplication) { + if (f instanceof Multiplication) expr = ((Multiplication) f).getParameter2(); - } else if (f instanceof Subtraction || f instanceof SumSubtraction) { + else if (f instanceof Subtraction || f instanceof SumSubtraction) { expr = ((Multiplication) f).getParameter2(); - if (f instanceof Subtraction) { + if (f instanceof Subtraction) fromSubtraction = 1; - } else { + else fromSubtraction = 2; - } } if (f instanceof SumSubtraction) { - + } - Function fnc = expr; + final Function fnc = expr; if (fnc instanceof Sum) { - Function a = ((Sum)fnc).getParameter1(); - Function b = ((Sum)fnc).getParameter2(); - Function fnc2 = new Subtraction(root, new Multiplication(root, new Number(root, -1), a), b); + final Function a = ((Sum) fnc).getParameter1(); + final Function b = ((Sum) fnc).getParameter2(); + final Function fnc2 = new Subtraction(root, new Multiplication(root, new Number(root, -1), a), b); if (fromSubtraction > 0) { - subtraction = new Subtraction(root, ((FunctionOperator)f).getParameter1(), fnc2); + subtraction = new Subtraction(root, ((FunctionOperator) f).getParameter1(), fnc2); result.add(subtraction); - } else { + } else result.add(fnc2); - } } else if (fnc instanceof Subtraction) { - Function a = ((Subtraction)fnc).getParameter1(); - Function b = ((Subtraction)fnc).getParameter2(); - Function fnc2 = new Sum(root, new Multiplication(root, new Number(root, -1), a), b); + final Function a = ((Subtraction) fnc).getParameter1(); + final Function b = ((Subtraction) fnc).getParameter2(); + final Function fnc2 = new Sum(root, new Multiplication(root, new Number(root, -1), a), b); if (fromSubtraction > 0) { - subtraction = new Subtraction(root, ((FunctionOperator)f).getParameter1(), fnc2); + subtraction = new Subtraction(root, ((FunctionOperator) f).getParameter1(), fnc2); result.add(subtraction); - } else { + } else result.add(fnc2); - } } else if (fnc instanceof SumSubtraction) { - Function a = ((SumSubtraction)fnc).getParameter1(); - Function b = ((SumSubtraction)fnc).getParameter2(); - Function fnc2 = new Sum(root, new Multiplication(root, new Number(root, -1), a), b); - Function fnc3 = new Subtraction(root, new Multiplication(root, new Number(root, -1), a), b); + final Function a = ((SumSubtraction) fnc).getParameter1(); + final Function b = ((SumSubtraction) fnc).getParameter2(); + final Function fnc2 = new Sum(root, new Multiplication(root, new Number(root, -1), a), b); + final Function fnc3 = new Subtraction(root, new Multiplication(root, new Number(root, -1), a), b); if (fromSubtraction > 0) { - subtraction = new SumSubtraction(root, ((FunctionOperator)f).getParameter1(), fnc2); + subtraction = new SumSubtraction(root, ((FunctionOperator) f).getParameter1(), fnc2); result.add(subtraction); - subtraction = new SumSubtraction(root, ((FunctionOperator)f).getParameter1(), fnc3); + subtraction = new SumSubtraction(root, ((FunctionOperator) f).getParameter1(), fnc3); result.add(subtraction); result.add(subtraction); } else { @@ -130,9 +123,8 @@ public class ExpandRule1 implements Rule { } } return result; - } else { + } else return null; - } - + } } diff --git a/rules/src/main/java/rules/ExpandRule2.java b/rules/src/main/java/rules/ExpandRule2.java index 84e5cf80..8089f77a 100644 --- a/rules/src/main/java/rules/ExpandRule2.java +++ b/rules/src/main/java/rules/ExpandRule2.java @@ -17,7 +17,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Expand rule * a(b+c)=ab+ac - * + * * @author Andrea Cavalli * */ @@ -40,22 +40,21 @@ public class ExpandRule2 implements Rule { - An ObjectArrayList if it did something */ @Override - public ObjectArrayList execute(Function f) throws Error { + public ObjectArrayList execute(final Function f) throws Error { boolean isExecutable = false; if (f instanceof Multiplication) { final Multiplication fnc = (Multiplication) f; - if (fnc.getParameter1() instanceof Sum) { + if (fnc.getParameter1() instanceof Sum) isExecutable = true; - } else if (fnc.getParameter2() instanceof Sum) { + else if (fnc.getParameter2() instanceof Sum) isExecutable = true; - } else { + else isExecutable = false; - } } if (isExecutable) { - ObjectArrayList result = new ObjectArrayList<>(); - MathContext root = f.getMathContext(); - + final ObjectArrayList result = new ObjectArrayList<>(); + final MathContext root = f.getMathContext(); + final Multiplication fnc = (Multiplication) f; final Sum sum; final Function a; @@ -65,9 +64,8 @@ public class ExpandRule2 implements Rule { } else if (fnc.getParameter2() instanceof Sum) { sum = (Sum) fnc.getParameter2(); a = fnc.getParameter1(); - } else { + } else throw new Error(Errors.UNBALANCED_STACK); - } final Function b = sum.getParameter1(); final Function c = sum.getParameter2(); @@ -75,9 +73,8 @@ public class ExpandRule2 implements Rule { final Multiplication ac = new Multiplication(root, a, c); result.add(new Sum(root, ab, ac)); return result; - } else { + } else return null; - } - + } } diff --git a/rules/src/main/java/rules/ExpandRule5.java b/rules/src/main/java/rules/ExpandRule5.java index 33c251ae..1dcc6fd1 100644 --- a/rules/src/main/java/rules/ExpandRule5.java +++ b/rules/src/main/java/rules/ExpandRule5.java @@ -17,7 +17,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Expand rule * -(-a) = a - * + * * @author Andrea Cavalli * */ @@ -40,30 +40,27 @@ public class ExpandRule5 implements Rule { - An ObjectArrayList if it did something */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; - if (f instanceof Negative) { - isExecutable = ((FunctionSingle)f).getParameter() instanceof Negative; - } else if (f instanceof Multiplication) { - if (((FunctionOperator)f).getParameter1().equals(new Number(f.getMathContext(), -1)) && ((FunctionOperator)f).getParameter2() instanceof Multiplication) { - isExecutable = ((FunctionOperator)((FunctionOperator)f).getParameter2()).getParameter1().equals(((FunctionOperator)f).getParameter1()); - } - } - + if (f instanceof Negative) + isExecutable = ((FunctionSingle) f).getParameter() instanceof Negative; + else if (f instanceof Multiplication) + if (((FunctionOperator) f).getParameter1().equals(new Number(f.getMathContext(), -1)) && ((FunctionOperator) f).getParameter2() instanceof Multiplication) + isExecutable = ((FunctionOperator) ((FunctionOperator) f).getParameter2()).getParameter1().equals(((FunctionOperator) f).getParameter1()); + if (isExecutable) { - ObjectArrayList result = new ObjectArrayList<>(); - + final ObjectArrayList result = new ObjectArrayList<>(); + if (f instanceof Negative) { - Negative fnc = (Negative) f; - result.add(((FunctionSingle)((FunctionSingle)fnc.getParameter()).getParameter()).getParameter()); + final Negative fnc = (Negative) f; + result.add(((FunctionSingle) ((FunctionSingle) fnc.getParameter()).getParameter()).getParameter()); } else if (f instanceof Multiplication) { - FunctionOperator fnc = (FunctionOperator) f; - result.add(((FunctionOperator)fnc.getParameter2()).getParameter2()); + final FunctionOperator fnc = (FunctionOperator) f; + result.add(((FunctionOperator) fnc.getParameter2()).getParameter2()); } return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/ExponentRule1.java b/rules/src/main/java/rules/ExponentRule1.java index bdad2314..41a452e8 100644 --- a/rules/src/main/java/rules/ExponentRule1.java +++ b/rules/src/main/java/rules/ExponentRule1.java @@ -15,7 +15,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Exponent rule * 1^a=1 - * + * * @author Andrea Cavalli * */ @@ -38,22 +38,19 @@ public class ExponentRule1 implements Rule { - An ObjectArrayList if it did something */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; - MathContext root = f.getMathContext(); - if (f instanceof Power) { - if (((Power)f).getParameter1().equals(new Number(root, 1))) { + final MathContext root = f.getMathContext(); + if (f instanceof Power) + if (((Power) f).getParameter1().equals(new Number(root, 1))) isExecutable = true; - } - } - + if (isExecutable) { - ObjectArrayList result = new ObjectArrayList<>(); + final ObjectArrayList result = new ObjectArrayList<>(); result.add(new Number(root, 1)); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/ExponentRule15.java b/rules/src/main/java/rules/ExponentRule15.java index 88e6296e..e561d707 100644 --- a/rules/src/main/java/rules/ExponentRule15.java +++ b/rules/src/main/java/rules/ExponentRule15.java @@ -17,7 +17,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Exponent rule * a*a=a^2 - * + * * @author Andrea Cavalli * */ @@ -41,26 +41,24 @@ public class ExponentRule15 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Multiplication) { - FunctionOperator fnc = (FunctionOperator) f; - if (fnc.getParameter1().equals(fnc.getParameter2())) { + final FunctionOperator fnc = (FunctionOperator) f; + if (fnc.getParameter1().equals(fnc.getParameter2())) isExecutable = true; - } } - + if (isExecutable) { - MathContext root = f.getMathContext(); - ObjectArrayList result = new ObjectArrayList<>(); - FunctionOperator fnc = (FunctionOperator) f; - Function a = fnc.getParameter1(); - Function two = new Number(root, 2); - Function p = new Power(root, a, two); - result.add(p); - return result; - } else { + final MathContext root = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); + final FunctionOperator fnc = (FunctionOperator) f; + final Function a = fnc.getParameter1(); + final Function two = new Number(root, 2); + final Function p = new Power(root, a, two); + result.add(p); + return result; + } else return null; - } } } diff --git a/rules/src/main/java/rules/ExponentRule16.java b/rules/src/main/java/rules/ExponentRule16.java index ecababa6..c8ff7e25 100644 --- a/rules/src/main/java/rules/ExponentRule16.java +++ b/rules/src/main/java/rules/ExponentRule16.java @@ -18,7 +18,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Exponent rule * (a ^ b) * (a ^ c) = a ^ (b + c) - * + * * @author Andrea Cavalli * */ @@ -42,33 +42,30 @@ public class ExponentRule16 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Multiplication) { - FunctionOperator fnc = (FunctionOperator) f; - if (fnc.getParameter1() instanceof Power && fnc.getParameter2() instanceof Power) { - isExecutable = ((FunctionOperator)fnc.getParameter1()).getParameter1().equals(((FunctionOperator)fnc.getParameter2()).getParameter1()); - } else if (fnc.getParameter1() instanceof Power) { - isExecutable = ((FunctionOperator)fnc.getParameter1()).getParameter1().equals(fnc.getParameter2()); - } else if (fnc.getParameter2() instanceof Power) { - isExecutable = ((FunctionOperator)fnc.getParameter2()).getParameter1().equals(fnc.getParameter1()); - } + final FunctionOperator fnc = (FunctionOperator) f; + if (fnc.getParameter1() instanceof Power && fnc.getParameter2() instanceof Power) + isExecutable = ((FunctionOperator) fnc.getParameter1()).getParameter1().equals(((FunctionOperator) fnc.getParameter2()).getParameter1()); + else if (fnc.getParameter1() instanceof Power) + isExecutable = ((FunctionOperator) fnc.getParameter1()).getParameter1().equals(fnc.getParameter2()); + else if (fnc.getParameter2() instanceof Power) + isExecutable = ((FunctionOperator) fnc.getParameter2()).getParameter1().equals(fnc.getParameter1()); } - + if (isExecutable) { - MathContext root = f.getMathContext(); - ObjectArrayList result = new ObjectArrayList<>(); - FunctionOperator fnc = (FunctionOperator) f; - if (fnc.getParameter1() instanceof Power && fnc.getParameter2() instanceof Power) { - result.add(new Power(root, ((FunctionOperator)fnc.getParameter1()).getParameter1(), new Sum(root, ((FunctionOperator)fnc.getParameter1()).getParameter2(), ((FunctionOperator)fnc.getParameter2()).getParameter2()))); - } else if (fnc.getParameter1() instanceof Power) { - result.add(new Power(root, fnc.getParameter2(), new Sum(root, ((FunctionOperator)fnc.getParameter1()).getParameter2(), new Number(root, 1)))); - } else if (fnc.getParameter2() instanceof Power) { - result.add(new Power(root, fnc.getParameter1(), new Sum(root, new Number(root, 1), ((FunctionOperator)fnc.getParameter2()).getParameter2()))); - } + final MathContext root = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); + final FunctionOperator fnc = (FunctionOperator) f; + if (fnc.getParameter1() instanceof Power && fnc.getParameter2() instanceof Power) + result.add(new Power(root, ((FunctionOperator) fnc.getParameter1()).getParameter1(), new Sum(root, ((FunctionOperator) fnc.getParameter1()).getParameter2(), ((FunctionOperator) fnc.getParameter2()).getParameter2()))); + else if (fnc.getParameter1() instanceof Power) + result.add(new Power(root, fnc.getParameter2(), new Sum(root, ((FunctionOperator) fnc.getParameter1()).getParameter2(), new Number(root, 1)))); + else if (fnc.getParameter2() instanceof Power) + result.add(new Power(root, fnc.getParameter1(), new Sum(root, new Number(root, 1), ((FunctionOperator) fnc.getParameter2()).getParameter2()))); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/ExponentRule17.java b/rules/src/main/java/rules/ExponentRule17.java index 8770bc47..b3784bad 100644 --- a/rules/src/main/java/rules/ExponentRule17.java +++ b/rules/src/main/java/rules/ExponentRule17.java @@ -17,7 +17,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Exponent rule * a√x=x^1/a - * + * * @author Andrea Cavalli * */ @@ -41,26 +41,24 @@ public class ExponentRule17 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Root) { - FunctionOperator fnc = (FunctionOperator) f; - if (fnc.getParameter1().equals(fnc.getParameter2())) { + final FunctionOperator fnc = (FunctionOperator) f; + if (fnc.getParameter1().equals(fnc.getParameter2())) isExecutable = true; - } } - + if (isExecutable) { - MathContext root = f.getMathContext(); - ObjectArrayList result = new ObjectArrayList<>(); - FunctionOperator fnc = (FunctionOperator) f; - Function a = fnc.getParameter1(); - Function two = new Number(root, 2); - Function p = new Power(root, a, two); + final MathContext root = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); + final FunctionOperator fnc = (FunctionOperator) f; + final Function a = fnc.getParameter1(); + final Function two = new Number(root, 2); + final Function p = new Power(root, a, two); result.add(p); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/ExponentRule2.java b/rules/src/main/java/rules/ExponentRule2.java index 392ba636..cb2d949e 100644 --- a/rules/src/main/java/rules/ExponentRule2.java +++ b/rules/src/main/java/rules/ExponentRule2.java @@ -15,7 +15,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Exponent rule * a^1=a - * + * * @author Andrea Cavalli * */ @@ -39,21 +39,19 @@ public class ExponentRule2 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Power) { - FunctionOperator fnc = (FunctionOperator) f; - if (fnc.getParameter2().equals(new Number(f.getMathContext(), 1))) { + final FunctionOperator fnc = (FunctionOperator) f; + if (fnc.getParameter2().equals(new Number(f.getMathContext(), 1))) isExecutable = true; - } } - + if (isExecutable) { - ObjectArrayList result = new ObjectArrayList<>(); - result.add(((FunctionOperator)f).getParameter1()); + final ObjectArrayList result = new ObjectArrayList<>(); + result.add(((FunctionOperator) f).getParameter1()); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/ExponentRule3.java b/rules/src/main/java/rules/ExponentRule3.java index 7bbbc96f..02e7d633 100644 --- a/rules/src/main/java/rules/ExponentRule3.java +++ b/rules/src/main/java/rules/ExponentRule3.java @@ -15,7 +15,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Exponent rule * a^0=1 - * + * * @author Andrea Cavalli * */ @@ -39,21 +39,19 @@ public class ExponentRule3 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Power) { - FunctionOperator fnc = (FunctionOperator) f; - if (fnc.getParameter2().equals(new Number(f.getMathContext(), 0))) { + final FunctionOperator fnc = (FunctionOperator) f; + if (fnc.getParameter2().equals(new Number(f.getMathContext(), 0))) isExecutable = true; - } } - + if (isExecutable) { - ObjectArrayList result = new ObjectArrayList<>(); + final ObjectArrayList result = new ObjectArrayList<>(); result.add(new Number(f.getMathContext(), 1)); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/ExponentRule4.java b/rules/src/main/java/rules/ExponentRule4.java index 2341ed2b..55d58c19 100644 --- a/rules/src/main/java/rules/ExponentRule4.java +++ b/rules/src/main/java/rules/ExponentRule4.java @@ -17,7 +17,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Exponent rule * (a*b)^n=a^n*b^n - * + * * @author Andrea Cavalli * */ @@ -41,30 +41,28 @@ public class ExponentRule4 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Power) { - FunctionOperator fnc = (FunctionOperator) f; - if (fnc.getParameter1() instanceof Multiplication && fnc.getParameter2() instanceof Number) { + final FunctionOperator fnc = (FunctionOperator) f; + if (fnc.getParameter1() instanceof Multiplication && fnc.getParameter2() instanceof Number) isExecutable = true; - } } - + if (isExecutable) { - MathContext root = f.getMathContext(); - ObjectArrayList result = new ObjectArrayList<>(); - FunctionOperator fnc = (FunctionOperator) f; - FunctionOperator mult = (FunctionOperator) fnc.getParameter1(); - Function a = mult.getParameter1(); - Function b = mult.getParameter2(); - Function n = fnc.getParameter2(); - Function p1 = new Power(root, a, n); - Function p2 = new Power(root, b, n); - Function retMult = new Multiplication(root, p1, p2); + final MathContext root = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); + final FunctionOperator fnc = (FunctionOperator) f; + final FunctionOperator mult = (FunctionOperator) fnc.getParameter1(); + final Function a = mult.getParameter1(); + final Function b = mult.getParameter2(); + final Function n = fnc.getParameter2(); + final Function p1 = new Power(root, a, n); + final Function p2 = new Power(root, b, n); + final Function retMult = new Multiplication(root, p1, p2); result.add(retMult); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/ExponentRule8.java b/rules/src/main/java/rules/ExponentRule8.java index 6af301da..c8be4247 100644 --- a/rules/src/main/java/rules/ExponentRule8.java +++ b/rules/src/main/java/rules/ExponentRule8.java @@ -17,7 +17,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Exponent rule * (a) ^ (b+c) = a ^ b + a ^ c - * + * * @author Andrea Cavalli * */ @@ -41,22 +41,21 @@ public class ExponentRule8 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { - boolean isExecutable = false; + public ObjectArrayList execute(final Function f) { if (f instanceof Power) { - FunctionOperator fnc = (FunctionOperator) f; + final FunctionOperator fnc = (FunctionOperator) f; if (fnc.getParameter2() instanceof Sum) { - Sum sum = (Sum) fnc.getParameter2(); - MathContext root = f.getMathContext(); - ObjectArrayList result = new ObjectArrayList<>(); - Function a = fnc.getParameter1(); - Function b = sum.getParameter1(); - Function c = sum.getParameter2(); + final Sum sum = (Sum) fnc.getParameter2(); + final MathContext root = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); + final Function a = fnc.getParameter1(); + final Function b = sum.getParameter1(); + final Function c = sum.getParameter2(); result.add(new Multiplication(root, new Power(root, a, b), new Power(root, a, c))); return result; } } - + return null; } } diff --git a/rules/src/main/java/rules/ExponentRule9.java b/rules/src/main/java/rules/ExponentRule9.java index 00add140..6dbee00a 100644 --- a/rules/src/main/java/rules/ExponentRule9.java +++ b/rules/src/main/java/rules/ExponentRule9.java @@ -16,7 +16,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Exponent rule * (a ^ b) ^ c = a ^ (b * c) - * + * * @author Andrea Cavalli * */ @@ -40,25 +40,23 @@ public class ExponentRule9 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Power) { - FunctionOperator fnc = (FunctionOperator) f; - if (fnc.getParameter1() instanceof Power) { + final FunctionOperator fnc = (FunctionOperator) f; + if (fnc.getParameter1() instanceof Power) isExecutable = true; - } } - + if (isExecutable) { - MathContext root = f.getMathContext(); - ObjectArrayList result = new ObjectArrayList<>(); - FunctionOperator powC = (FunctionOperator) f; - FunctionOperator powB = (FunctionOperator) powC.getParameter1(); - Function p = new Power(root, powB.getParameter1(), new Multiplication(root, powB.getParameter2(), powC.getParameter2())); + final MathContext root = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); + final FunctionOperator powC = (FunctionOperator) f; + final FunctionOperator powB = (FunctionOperator) powC.getParameter1(); + final Function p = new Power(root, powB.getParameter1(), new Multiplication(root, powB.getParameter2(), powC.getParameter2())); result.add(p); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/FractionsRule1.java b/rules/src/main/java/rules/FractionsRule1.java index 65ff3b31..5057683b 100644 --- a/rules/src/main/java/rules/FractionsRule1.java +++ b/rules/src/main/java/rules/FractionsRule1.java @@ -16,7 +16,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Fractions rule * 0 / a = 0 - * + * * @author Andrea Cavalli * */ @@ -40,32 +40,28 @@ public class FractionsRule1 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; - MathContext root = f.getMathContext(); + final MathContext root = f.getMathContext(); if (f instanceof Division) { - FunctionOperator fnc = (FunctionOperator) f; + final FunctionOperator fnc = (FunctionOperator) f; if (fnc.getParameter1() instanceof Number) { - Function numb1 = fnc.getParameter1(); - if (numb1.equals(new Number(root, 0))) { + final Function numb1 = fnc.getParameter1(); + if (numb1.equals(new Number(root, 0))) if (fnc.getParameter2() instanceof Number) { - Function numb2 = fnc.getParameter2(); - if (numb2.equals(new Number(root, 0)) == false) { + final Function numb2 = fnc.getParameter2(); + if (numb2.equals(new Number(root, 0)) == false) isExecutable = true; - } - } else { + } else isExecutable = true; - } - } } } - + if (isExecutable) { - ObjectArrayList result = new ObjectArrayList<>(); + final ObjectArrayList result = new ObjectArrayList<>(); result.add(new Number(f.getMathContext(), 0)); return result; - } else { + } else return null; - } } } \ No newline at end of file diff --git a/rules/src/main/java/rules/FractionsRule10.java b/rules/src/main/java/rules/FractionsRule10.java index af19b42f..239234f5 100644 --- a/rules/src/main/java/rules/FractionsRule10.java +++ b/rules/src/main/java/rules/FractionsRule10.java @@ -15,7 +15,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Number rule * a/(-b) = -(a/b) - * + * * @author Andrea Cavalli * */ @@ -39,17 +39,17 @@ public class FractionsRule10 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { if (f instanceof Division) { - MathContext root = f.getMathContext(); - Division div = (Division) f; - if (div.getParameter2() instanceof Multiplication && ((Multiplication)div.getParameter2()).isNegative()) { - ObjectArrayList result = new ObjectArrayList<>(); - result.add(Multiplication.newNegative(root, new Division(root, div.getParameter1(), ((Multiplication)div.getParameter2()).toPositive()))); + final MathContext root = f.getMathContext(); + final Division div = (Division) f; + if (div.getParameter2() instanceof Multiplication && ((Multiplication) div.getParameter2()).isNegative()) { + final ObjectArrayList result = new ObjectArrayList<>(); + result.add(Multiplication.newNegative(root, new Division(root, div.getParameter1(), ((Multiplication) div.getParameter2()).toPositive()))); return result; } } - + return null; } } diff --git a/rules/src/main/java/rules/FractionsRule11.java b/rules/src/main/java/rules/FractionsRule11.java index 0ff7fcf0..0552da03 100644 --- a/rules/src/main/java/rules/FractionsRule11.java +++ b/rules/src/main/java/rules/FractionsRule11.java @@ -15,7 +15,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Fractions rule * a / (b / c) = (a * c) / b - * + * * @author Andrea Cavalli * */ @@ -39,11 +39,13 @@ public class FractionsRule11 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Division) { - FunctionOperator fnc = (FunctionOperator) f; + final FunctionOperator fnc = (FunctionOperator) f; + @SuppressWarnings("unused") Function a; + @SuppressWarnings("unused") Function c; FunctionOperator div2; if (fnc.getParameter2() instanceof Division) { @@ -51,27 +53,25 @@ public class FractionsRule11 implements Rule { a = fnc.getParameter1(); c = div2.getParameter2(); isExecutable = true; - } else { + } else isExecutable = false; - } } if (isExecutable) { - ObjectArrayList result = new ObjectArrayList<>(); - FunctionOperator fnc = (FunctionOperator) f; + final ObjectArrayList result = new ObjectArrayList<>(); + final FunctionOperator fnc = (FunctionOperator) f; Function a; Function b; Function c; - - FunctionOperator div2 = (FunctionOperator) fnc.getParameter2(); - + + final FunctionOperator div2 = (FunctionOperator) fnc.getParameter2(); + a = fnc.getParameter1(); b = div2.getParameter1(); c = div2.getParameter2(); result.add(new Division(fnc.getMathContext(), new Multiplication(fnc.getMathContext(), a, c), b)); - + return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/FractionsRule12.java b/rules/src/main/java/rules/FractionsRule12.java index 1b4f46ee..764c2348 100644 --- a/rules/src/main/java/rules/FractionsRule12.java +++ b/rules/src/main/java/rules/FractionsRule12.java @@ -15,7 +15,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Fractions rule * (b / c) / a = b / (a * c) - * + * * @author Andrea Cavalli * */ @@ -39,36 +39,37 @@ public class FractionsRule12 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Division) { - FunctionOperator fnc = (FunctionOperator) f; + final FunctionOperator fnc = (FunctionOperator) f; + @SuppressWarnings("unused") Function a; + @SuppressWarnings("unused") Function c; if (fnc.getParameter1() instanceof Division) { - FunctionOperator div2 = (FunctionOperator) fnc.getParameter1(); + final FunctionOperator div2 = (FunctionOperator) fnc.getParameter1(); a = fnc.getParameter1(); c = div2.getParameter2(); isExecutable = true; } } - + if (isExecutable) { - ObjectArrayList result = new ObjectArrayList<>(); - FunctionOperator fnc = (FunctionOperator) f; + final ObjectArrayList result = new ObjectArrayList<>(); + final FunctionOperator fnc = (FunctionOperator) f; Function a; Function b; Function c; - - FunctionOperator div2 = (FunctionOperator) fnc.getParameter1(); + + final FunctionOperator div2 = (FunctionOperator) fnc.getParameter1(); a = fnc.getParameter2(); b = div2.getParameter1(); c = div2.getParameter2(); result.add(new Division(fnc.getMathContext(), b, new Multiplication(fnc.getMathContext(), c, a))); - + return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/FractionsRule14.java b/rules/src/main/java/rules/FractionsRule14.java index f9110be0..5c5ff483 100644 --- a/rules/src/main/java/rules/FractionsRule14.java +++ b/rules/src/main/java/rules/FractionsRule14.java @@ -15,7 +15,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Fractions rule * (a / b) * (c / d) = (a * c) / (b * d) - * + * * @author Andrea Cavalli * */ @@ -39,72 +39,75 @@ public class FractionsRule14 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Multiplication) { - FunctionOperator fnc = (FunctionOperator) f; + final FunctionOperator fnc = (FunctionOperator) f; + @SuppressWarnings("unused") Function a; + @SuppressWarnings("unused") Function b; + @SuppressWarnings("unused") Function c; + @SuppressWarnings("unused") Function d; if (fnc.getParameter1() instanceof Division && fnc.getParameter2() instanceof Division) { - FunctionOperator div1 = (FunctionOperator) fnc.getParameter1(); - FunctionOperator div2 = (FunctionOperator) fnc.getParameter2(); + final FunctionOperator div1 = (FunctionOperator) fnc.getParameter1(); + final FunctionOperator div2 = (FunctionOperator) fnc.getParameter2(); a = div1.getParameter1(); b = div1.getParameter2(); c = div2.getParameter1(); d = div2.getParameter2(); isExecutable = true; } else if (fnc.getParameter1() instanceof Division) { - FunctionOperator div1 = (FunctionOperator) fnc.getParameter1(); + final FunctionOperator div1 = (FunctionOperator) fnc.getParameter1(); a = div1.getParameter1(); b = div1.getParameter2(); c = fnc.getParameter2(); isExecutable = true; } else if (fnc.getParameter2() instanceof Division) { - FunctionOperator div2 = (FunctionOperator) fnc.getParameter2(); + final FunctionOperator div2 = (FunctionOperator) fnc.getParameter2(); a = fnc.getParameter1(); c = div2.getParameter1(); d = div2.getParameter2(); isExecutable = true; } } - + if (isExecutable) { - ObjectArrayList result = new ObjectArrayList<>(); - FunctionOperator fnc = (FunctionOperator) f; + final ObjectArrayList result = new ObjectArrayList<>(); + final FunctionOperator fnc = (FunctionOperator) f; Function a; Function b; Function c; Function d; - + if (fnc.getParameter1() instanceof Division && fnc.getParameter2() instanceof Division) { - FunctionOperator div1 = (FunctionOperator) fnc.getParameter1(); - FunctionOperator div2 = (FunctionOperator) fnc.getParameter2(); + final FunctionOperator div1 = (FunctionOperator) fnc.getParameter1(); + final FunctionOperator div2 = (FunctionOperator) fnc.getParameter2(); a = div1.getParameter1(); b = div1.getParameter2(); c = div2.getParameter1(); d = div2.getParameter2(); - Function div = new Division(fnc.getMathContext(), new Multiplication(fnc.getMathContext(), a, c), new Multiplication(fnc.getMathContext(), b, d)); + final Function div = new Division(fnc.getMathContext(), new Multiplication(fnc.getMathContext(), a, c), new Multiplication(fnc.getMathContext(), b, d)); result.add(div); } else if (fnc.getParameter1() instanceof Division) { - FunctionOperator div1 = (FunctionOperator) fnc.getParameter1(); + final FunctionOperator div1 = (FunctionOperator) fnc.getParameter1(); a = div1.getParameter1(); b = div1.getParameter2(); c = fnc.getParameter2(); - Function div = new Division(fnc.getMathContext(), new Multiplication(fnc.getMathContext(), a, c), b); + final Function div = new Division(fnc.getMathContext(), new Multiplication(fnc.getMathContext(), a, c), b); result.add(div); } else if (fnc.getParameter2() instanceof Division) { - FunctionOperator div2 = (FunctionOperator) fnc.getParameter2(); + final FunctionOperator div2 = (FunctionOperator) fnc.getParameter2(); a = fnc.getParameter1(); c = div2.getParameter1(); d = div2.getParameter2(); - Function div = new Division(fnc.getMathContext(), new Multiplication(fnc.getMathContext(), a, c), d); + final Function div = new Division(fnc.getMathContext(), new Multiplication(fnc.getMathContext(), a, c), d); result.add(div); } return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/FractionsRule2.java b/rules/src/main/java/rules/FractionsRule2.java index 17be54df..5659a617 100644 --- a/rules/src/main/java/rules/FractionsRule2.java +++ b/rules/src/main/java/rules/FractionsRule2.java @@ -14,7 +14,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Fractions rule * a / 1 = a - * + * * @author Andrea Cavalli * */ @@ -38,25 +38,23 @@ public class FractionsRule2 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Division) { - Division fnc = (Division) f; + final Division fnc = (Division) f; if (fnc.getParameter2() instanceof Number) { - Number numb = (Number) fnc.getParameter2(); - if (numb.equals(new Number(f.getMathContext(), 1))) { + final Number numb = (Number) fnc.getParameter2(); + if (numb.equals(new Number(f.getMathContext(), 1))) isExecutable = true; - } } } - + if (isExecutable) { - ObjectArrayList result = new ObjectArrayList<>(); - Division fnc = (Division) f; + final ObjectArrayList result = new ObjectArrayList<>(); + final Division fnc = (Division) f; result.add(fnc.getParameter1()); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/FractionsRule3.java b/rules/src/main/java/rules/FractionsRule3.java index 81de1799..b9dc2180 100644 --- a/rules/src/main/java/rules/FractionsRule3.java +++ b/rules/src/main/java/rules/FractionsRule3.java @@ -15,7 +15,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Fractions rule * a / a = 1 - * + * * @author Andrea Cavalli * */ @@ -39,21 +39,19 @@ public class FractionsRule3 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Division) { - FunctionOperator fnc = (FunctionOperator) f; - if (fnc.getParameter1().equals(fnc.getParameter2())) { + final FunctionOperator fnc = (FunctionOperator) f; + if (fnc.getParameter1().equals(fnc.getParameter2())) isExecutable = true; - } } - + if (isExecutable) { - ObjectArrayList result = new ObjectArrayList<>(); + final ObjectArrayList result = new ObjectArrayList<>(); result.add(new Number(f.getMathContext(), 1)); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/FractionsRule4.java b/rules/src/main/java/rules/FractionsRule4.java index b60c76d3..e5472f66 100644 --- a/rules/src/main/java/rules/FractionsRule4.java +++ b/rules/src/main/java/rules/FractionsRule4.java @@ -16,7 +16,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Fractions rule * (a / b) ^ -1 = b / a - * + * * @author Andrea Cavalli * */ @@ -40,28 +40,26 @@ public class FractionsRule4 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Power) { - FunctionOperator fnc = (FunctionOperator) f; + final FunctionOperator fnc = (FunctionOperator) f; if (fnc.getParameter1() instanceof Division && fnc.getParameter2() instanceof Number) { - Function n2 = fnc.getParameter2(); - if (n2.equals(new Number(f.getMathContext(), -1))) { + final Function n2 = fnc.getParameter2(); + if (n2.equals(new Number(f.getMathContext(), -1))) isExecutable = true; - } } } - + if (isExecutable) { - ObjectArrayList result = new ObjectArrayList<>(); - FunctionOperator fnc = (FunctionOperator) f; - Function a = ((FunctionOperator) fnc.getParameter1()).getParameter1(); - Function b = ((FunctionOperator) fnc.getParameter1()).getParameter2(); - Function res = new Division(f.getMathContext(), b, a); + final ObjectArrayList result = new ObjectArrayList<>(); + final FunctionOperator fnc = (FunctionOperator) f; + final Function a = ((FunctionOperator) fnc.getParameter1()).getParameter1(); + final Function b = ((FunctionOperator) fnc.getParameter1()).getParameter2(); + final Function res = new Division(f.getMathContext(), b, a); result.add(res); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/FractionsRule5.java b/rules/src/main/java/rules/FractionsRule5.java index 6fca1e67..2d13bba6 100644 --- a/rules/src/main/java/rules/FractionsRule5.java +++ b/rules/src/main/java/rules/FractionsRule5.java @@ -21,7 +21,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Fractions rule * (a / b) ^ -c = (b / a) ^ c - * + * * @author Andrea Cavalli * */ @@ -45,40 +45,36 @@ public class FractionsRule5 implements Rule { */ @Override - public ObjectArrayList execute(Function f) throws Error { + public ObjectArrayList execute(final Function f) throws Error { boolean isExecutable = false; if (f instanceof Power) { - FunctionOperator fnc = (FunctionOperator) f; - if (fnc.getParameter1() instanceof Division) { - if (fnc.getParameter2() instanceof Multiplication && ((FunctionOperator) fnc.getParameter2()).getParameter1().equals(new Number(f.getMathContext(), -1))) { + final FunctionOperator fnc = (FunctionOperator) f; + if (fnc.getParameter1() instanceof Division) + if (fnc.getParameter2() instanceof Multiplication && ((FunctionOperator) fnc.getParameter2()).getParameter1().equals(new Number(f.getMathContext(), -1))) isExecutable = true; - } else if (fnc.getParameter2() instanceof Number) { - Number n2 = (Number) fnc.getParameter2(); - if (n2.getTerm().compareTo(BigDecimal.ZERO) < 0) { + else if (fnc.getParameter2() instanceof Number) { + final Number n2 = (Number) fnc.getParameter2(); + if (n2.getTerm().compareTo(BigDecimal.ZERO) < 0) isExecutable = true; - } } - } } if (isExecutable) { - MathContext root = f.getMathContext(); - ObjectArrayList result = new ObjectArrayList<>(); - FunctionOperator fnc = (FunctionOperator) f; - Function a = ((FunctionOperator) fnc.getParameter1()).getParameter1(); - Function b = ((FunctionOperator) fnc.getParameter1()).getParameter2(); + final MathContext root = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); + final FunctionOperator fnc = (FunctionOperator) f; + final Function a = ((FunctionOperator) fnc.getParameter1()).getParameter1(); + final Function b = ((FunctionOperator) fnc.getParameter1()).getParameter2(); Function c; - if (fnc.getParameter2() instanceof Multiplication) { + if (fnc.getParameter2() instanceof Multiplication) c = ((FunctionOperator) fnc.getParameter2()).getParameter2(); - } else { + else c = ((Number) fnc.getParameter2()).multiply(new Number(root, "-1")); - } - Function dv = new Division(root, b, a); - Function pow = new Power(root, dv, c); + final Function dv = new Division(root, b, a); + final Function pow = new Power(root, dv, c); result.add(pow); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/FractionsRule6.java b/rules/src/main/java/rules/FractionsRule6.java index f40da47c..0dc2ec4f 100644 --- a/rules/src/main/java/rules/FractionsRule6.java +++ b/rules/src/main/java/rules/FractionsRule6.java @@ -16,7 +16,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Number rule * a ^ -1 = 1/a - * + * * @author Andrea Cavalli * */ @@ -40,27 +40,25 @@ public class FractionsRule6 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Power) { - MathContext root = f.getMathContext(); - Power pow = (Power) f; + final MathContext root = f.getMathContext(); + final Power pow = (Power) f; if (pow.getParameter2() instanceof Number) { - Function numb = pow.getParameter2(); - if (numb.equals(new Number(root, -1))) { + final Function numb = pow.getParameter2(); + if (numb.equals(new Number(root, -1))) isExecutable = true; - } } } if (isExecutable) { - MathContext root = f.getMathContext(); - ObjectArrayList result = new ObjectArrayList<>(); - Function a = new Division(root, new Number(root, 1), ((Power) f).getParameter1()); + final MathContext root = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); + final Function a = new Division(root, new Number(root, 1), ((Power) f).getParameter1()); result.add(a); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/FractionsRule7.java b/rules/src/main/java/rules/FractionsRule7.java index 789c78ab..952924a3 100644 --- a/rules/src/main/java/rules/FractionsRule7.java +++ b/rules/src/main/java/rules/FractionsRule7.java @@ -19,7 +19,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Number rule * a ^ -b = 1/(a^b) - * + * * @author Andrea Cavalli * */ @@ -43,22 +43,21 @@ public class FractionsRule7 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { - boolean isExecutable = false; + public ObjectArrayList execute(final Function f) { if (f instanceof Power) { - MathContext root = f.getMathContext(); - Power pow = (Power) f; + final MathContext root = f.getMathContext(); + final Power pow = (Power) f; if (pow.getParameter2() instanceof Number) { - Number numb = (Number) pow.getParameter2(); + final Number numb = (Number) pow.getParameter2(); if (numb.getTerm().compareTo(BigDecimal.ZERO) < 0) { - ObjectArrayList result = new ObjectArrayList<>(); - Function a = new Division(root, new Number(root, 1), new Power(root, ((Power) f).getParameter1(), ((Number) ((Power) f).getParameter2()).multiply(new Number(root, -1)))); + final ObjectArrayList result = new ObjectArrayList<>(); + final Function a = new Division(root, new Number(root, 1), new Power(root, ((Power) f).getParameter1(), ((Number) ((Power) f).getParameter2()).multiply(new Number(root, -1)))); result.add(a); return result; } } else if (pow.getParameter2() instanceof Multiplication && ((Multiplication) pow.getParameter2()).getParameter1().equals(new Number(root, -1))) { - ObjectArrayList result = new ObjectArrayList<>(); - Function a = new Division(root, new Number(root, 1), new Power(root, ((Power) f).getParameter1(), ((Multiplication) ((Power) f).getParameter2()).getParameter2())); + final ObjectArrayList result = new ObjectArrayList<>(); + final Function a = new Division(root, new Number(root, 1), new Power(root, ((Power) f).getParameter1(), ((Multiplication) ((Power) f).getParameter2()).getParameter2())); result.add(a); return result; } diff --git a/rules/src/main/java/rules/FractionsRule8.java b/rules/src/main/java/rules/FractionsRule8.java index 636e38e9..15868512 100644 --- a/rules/src/main/java/rules/FractionsRule8.java +++ b/rules/src/main/java/rules/FractionsRule8.java @@ -15,7 +15,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Number rule * -a/-b = a/b - * + * * @author Andrea Cavalli * */ @@ -39,17 +39,16 @@ public class FractionsRule8 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { if (f instanceof Division) { - MathContext root = f.getMathContext(); - Division div = (Division) f; - if (div.getParameter1() instanceof Multiplication && ((Multiplication) div.getParameter1()).isNegative()) { + final MathContext root = f.getMathContext(); + final Division div = (Division) f; + if (div.getParameter1() instanceof Multiplication && ((Multiplication) div.getParameter1()).isNegative()) if (div.getParameter2() instanceof Multiplication && ((Multiplication) div.getParameter2()).isNegative()) { - ObjectArrayList result = new ObjectArrayList<>(); + final ObjectArrayList result = new ObjectArrayList<>(); result.add(new Division(root, ((Multiplication) div.getParameter1()).toPositive(), ((Multiplication) div.getParameter2()).toPositive())); return result; } - } } return null; diff --git a/rules/src/main/java/rules/FractionsRule9.java b/rules/src/main/java/rules/FractionsRule9.java index 263d77c8..c88cf09b 100644 --- a/rules/src/main/java/rules/FractionsRule9.java +++ b/rules/src/main/java/rules/FractionsRule9.java @@ -15,7 +15,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Number rule * (-a)/b = -(a/b) - * + * * @author Andrea Cavalli * */ @@ -39,12 +39,12 @@ public class FractionsRule9 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { if (f instanceof Division) { - MathContext root = f.getMathContext(); - Division div = (Division) f; + final MathContext root = f.getMathContext(); + final Division div = (Division) f; if (div.getParameter1() instanceof Multiplication && ((Multiplication) div.getParameter1()).isNegative()) { - ObjectArrayList result = new ObjectArrayList<>(); + final ObjectArrayList result = new ObjectArrayList<>(); result.add(Multiplication.newNegative(root, new Division(root, ((Multiplication) div.getParameter1()).toPositive(), div.getParameter2()))); return result; } diff --git a/rules/src/main/java/rules/NumberRule1.java b/rules/src/main/java/rules/NumberRule1.java index 346f20fd..5d9f79fa 100644 --- a/rules/src/main/java/rules/NumberRule1.java +++ b/rules/src/main/java/rules/NumberRule1.java @@ -16,7 +16,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Number rule * a * 0 = 0 - * + * * @author Andrea Cavalli * */ @@ -40,31 +40,28 @@ public class NumberRule1 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Multiplication) { - MathContext root = f.getMathContext(); - FunctionOperator mult = (FunctionOperator) f; + final MathContext root = f.getMathContext(); + final FunctionOperator mult = (FunctionOperator) f; if (mult.getParameter1() instanceof Number) { - Function numb = mult.getParameter1(); - if (numb.equals(new Number(root, 0))) { + final Function numb = mult.getParameter1(); + if (numb.equals(new Number(root, 0))) isExecutable = true; - } } if (mult.getParameter2() instanceof Number) { - Function numb = mult.getParameter2(); - if (numb.equals(new Number(root, 0))) { + final Function numb = mult.getParameter2(); + if (numb.equals(new Number(root, 0))) isExecutable = true; - } } } if (isExecutable) { - ObjectArrayList result = new ObjectArrayList<>(); + final ObjectArrayList result = new ObjectArrayList<>(); result.add(new Number(f.getMathContext(), 0)); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/NumberRule2.java b/rules/src/main/java/rules/NumberRule2.java index 357de0d9..a99d2fbc 100644 --- a/rules/src/main/java/rules/NumberRule2.java +++ b/rules/src/main/java/rules/NumberRule2.java @@ -15,7 +15,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Number rule * a * 1 = a - * + * * @author Andrea Cavalli * */ @@ -39,40 +39,38 @@ public class NumberRule2 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Multiplication) { - MathContext root = f.getMathContext(); - Multiplication mult = (Multiplication) f; + final MathContext root = f.getMathContext(); + final Multiplication mult = (Multiplication) f; if (mult.getParameter1() instanceof Number) { - Function numb = mult.getParameter1(); - if (numb.equals(new Number(root, 1))) { + final Function numb = mult.getParameter1(); + if (numb.equals(new Number(root, 1))) isExecutable = true; - } } if (mult.getParameter2() instanceof Number) { - Function numb = mult.getParameter2(); - if (numb.equals(new Number(root, 1))) { + final Function numb = mult.getParameter2(); + if (numb.equals(new Number(root, 1))) isExecutable = true; - } } } if (isExecutable) { - MathContext root = f.getMathContext(); - ObjectArrayList result = new ObjectArrayList<>(); + final MathContext root = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); Function a = null; boolean aFound = false; - Multiplication mult = (Multiplication) f; + final Multiplication mult = (Multiplication) f; if (aFound == false & mult.getParameter1() instanceof Number) { - Function numb = mult.getParameter1(); + final Function numb = mult.getParameter1(); if (numb.equals(new Number(root, 1))) { a = mult.getParameter2(); aFound = true; } } if (aFound == false && mult.getParameter2() instanceof Number) { - Function numb = mult.getParameter2(); + final Function numb = mult.getParameter2(); if (numb.equals(new Number(root, 1))) { a = mult.getParameter1(); aFound = true; @@ -81,8 +79,7 @@ public class NumberRule2 implements Rule { result.add(a); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/NumberRule3.java b/rules/src/main/java/rules/NumberRule3.java index c665e88e..088ceeae 100644 --- a/rules/src/main/java/rules/NumberRule3.java +++ b/rules/src/main/java/rules/NumberRule3.java @@ -21,7 +21,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; * a - a = 0 * -a + a = 0 * a ± a = {0, 2a} - * + * * @author Andrea Cavalli * */ @@ -45,41 +45,36 @@ public class NumberRule3 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Subtraction) { - FunctionOperator sub = (FunctionOperator) f; - if (sub.getParameter1().equals(sub.getParameter2())) { + final FunctionOperator sub = (FunctionOperator) f; + if (sub.getParameter1().equals(sub.getParameter2())) isExecutable = true; - } } else if (f instanceof Sum) { - FunctionOperator sub = (FunctionOperator) f; - if (sub.getParameter1() instanceof Multiplication) { + final FunctionOperator sub = (FunctionOperator) f; + if (sub.getParameter1() instanceof Multiplication) if (((FunctionOperator) sub.getParameter1()).getParameter1() instanceof Number && ((FunctionOperator) sub.getParameter1()).getParameter1().equals(new Number(f.getMathContext(), -1))) { - Function neg = ((FunctionOperator) sub.getParameter1()).getParameter2(); - if (neg.equals(sub.getParameter2())) { + final Function neg = ((FunctionOperator) sub.getParameter1()).getParameter2(); + if (neg.equals(sub.getParameter2())) isExecutable = true; - } } - } } else if (f instanceof SumSubtraction) { - FunctionOperator sub = (FunctionOperator) f; - if (sub.getParameter1().equals(sub.getParameter2())) { + final FunctionOperator sub = (FunctionOperator) f; + if (sub.getParameter1().equals(sub.getParameter2())) isExecutable = true; - } } if (isExecutable) { - MathContext root = f.getMathContext(); - ObjectArrayList result = new ObjectArrayList<>(); + final MathContext root = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); if (f instanceof SumSubtraction) { - Function mul = new Multiplication(root, new Number(root, 2), ((FunctionOperator) f).getParameter1()); + final Function mul = new Multiplication(root, new Number(root, 2), ((FunctionOperator) f).getParameter1()); result.add(mul); } result.add(new Number(root, 0)); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/NumberRule4.java b/rules/src/main/java/rules/NumberRule4.java index e297f867..6338c335 100644 --- a/rules/src/main/java/rules/NumberRule4.java +++ b/rules/src/main/java/rules/NumberRule4.java @@ -17,7 +17,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Number rule * a ± b = {a+b, a-b} - * + * * @author Andrea Cavalli * */ @@ -41,21 +41,19 @@ public class NumberRule4 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; - if (f instanceof SumSubtraction) { + if (f instanceof SumSubtraction) isExecutable = true; - } if (isExecutable) { - MathContext root = f.getMathContext(); - ObjectArrayList result = new ObjectArrayList<>(); - FunctionOperator ss = (FunctionOperator) f; + final MathContext root = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); + final FunctionOperator ss = (FunctionOperator) f; result.add(new Sum(root, ss.getParameter1(), ss.getParameter2())); result.add(new Subtraction(root, ss.getParameter1(), ss.getParameter2())); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/NumberRule5.java b/rules/src/main/java/rules/NumberRule5.java index 71ea8b5f..32d2f831 100644 --- a/rules/src/main/java/rules/NumberRule5.java +++ b/rules/src/main/java/rules/NumberRule5.java @@ -23,7 +23,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; * a - 0 = a * 0 - a = -a * a ± 0 = a - * + * * @author Andrea Cavalli * */ @@ -47,34 +47,29 @@ public class NumberRule5 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Sum || f instanceof Subtraction || f instanceof SumSubtraction) { - MathContext root = f.getMathContext(); - FunctionOperator fnc = (FunctionOperator) f; - if (fnc.getParameter1().equals(new Number(root, 0)) || fnc.getParameter2().equals(new Number(root, 0))) { - if (!(fnc.getParameter1().equals(new Number(root, 0)) && f instanceof SumSubtraction)) { + final MathContext root = f.getMathContext(); + final FunctionOperator fnc = (FunctionOperator) f; + if (fnc.getParameter1().equals(new Number(root, 0)) || fnc.getParameter2().equals(new Number(root, 0))) + if (!(fnc.getParameter1().equals(new Number(root, 0)) && f instanceof SumSubtraction)) isExecutable = true; - } - } } if (isExecutable) { - MathContext root = f.getMathContext(); - ObjectArrayList result = new ObjectArrayList<>(); - FunctionOperator fnc = (FunctionOperator) f; + final MathContext root = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); + final FunctionOperator fnc = (FunctionOperator) f; Function a = fnc.getParameter1(); - if (a.equals(new Number(root, 0))) { - if (f instanceof Subtraction) { + if (a.equals(new Number(root, 0))) + if (f instanceof Subtraction) a = new Multiplication(root, new Number(root, -1), fnc.getParameter2()); - } else { + else a = fnc.getParameter2(); - } - } result.add(a); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/NumberRule7.java b/rules/src/main/java/rules/NumberRule7.java index fbd8a00a..ae547f90 100644 --- a/rules/src/main/java/rules/NumberRule7.java +++ b/rules/src/main/java/rules/NumberRule7.java @@ -17,7 +17,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Number rule * a + a = 2a - * + * * @author Andrea Cavalli * */ @@ -41,20 +41,18 @@ public class NumberRule7 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; - if (f instanceof Sum) { + if (f instanceof Sum) isExecutable = ((FunctionOperator) f).getParameter1().equals(((FunctionOperator) f).getParameter2()); - } if (isExecutable) { - MathContext root = f.getMathContext(); - ObjectArrayList result = new ObjectArrayList<>(); - Function mult = new Multiplication(root, new Number(root, 2), ((FunctionOperator) f).getParameter1()); + final MathContext root = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); + final Function mult = new Multiplication(root, new Number(root, 2), ((FunctionOperator) f).getParameter1()); result.add(mult); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/UndefinedRule1.java b/rules/src/main/java/rules/UndefinedRule1.java index 49242209..38bb69bf 100644 --- a/rules/src/main/java/rules/UndefinedRule1.java +++ b/rules/src/main/java/rules/UndefinedRule1.java @@ -17,7 +17,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Undefined rule * 0^0=undefined - * + * * @author Andrea Cavalli * */ @@ -41,23 +41,21 @@ public class UndefinedRule1 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Power) { - MathContext root = f.getMathContext(); - FunctionOperator fnc = (FunctionOperator) f; - if (fnc.getParameter1().equals(new Number(root, 0)) && fnc.getParameter2().equals(new Number(root, 0))) { + final MathContext root = f.getMathContext(); + final FunctionOperator fnc = (FunctionOperator) f; + if (fnc.getParameter1().equals(new Number(root, 0)) && fnc.getParameter2().equals(new Number(root, 0))) isExecutable = true; - } } if (isExecutable) { - MathContext root = f.getMathContext(); - ObjectArrayList result = new ObjectArrayList<>(); + final MathContext root = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); result.add(new Undefined(root)); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/UndefinedRule2.java b/rules/src/main/java/rules/UndefinedRule2.java index d399c8d4..1ea2a1f8 100644 --- a/rules/src/main/java/rules/UndefinedRule2.java +++ b/rules/src/main/java/rules/UndefinedRule2.java @@ -17,7 +17,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Undefined rule * a / 0 = undefined - * + * * @author Andrea Cavalli * */ @@ -41,26 +41,24 @@ public class UndefinedRule2 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Division) { - MathContext root = f.getMathContext(); - FunctionOperator fnc = (FunctionOperator) f; + final MathContext root = f.getMathContext(); + final FunctionOperator fnc = (FunctionOperator) f; if (fnc.getParameter2() instanceof Number) { - Number numb = (Number) fnc.getParameter2(); - if (numb.equals(new Number(root, 0))) { + final Number numb = (Number) fnc.getParameter2(); + if (numb.equals(new Number(root, 0))) isExecutable = true; - } } } if (isExecutable) { - MathContext root = f.getMathContext(); - ObjectArrayList result = new ObjectArrayList<>(); + final MathContext root = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); result.add(new Undefined(root)); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/VariableRule1.java b/rules/src/main/java/rules/VariableRule1.java index 621b23e2..1bfd1c9b 100644 --- a/rules/src/main/java/rules/VariableRule1.java +++ b/rules/src/main/java/rules/VariableRule1.java @@ -17,7 +17,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Variable rule * ax+bx=(a+b)*x (a,b NUMBER; x VARIABLE|MULTIPLICATION) - * + * * @author Andrea Cavalli * */ @@ -41,25 +41,24 @@ public class VariableRule1 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Subtraction || f instanceof Sum) { - FunctionOperator fnc = (FunctionOperator) f; + final FunctionOperator fnc = (FunctionOperator) f; if (fnc.getParameter1() instanceof Multiplication & fnc.getParameter2() instanceof Multiplication) { - FunctionOperator m1 = (FunctionOperator) fnc.getParameter1(); - FunctionOperator m2 = (FunctionOperator) fnc.getParameter2(); - if (m1.getParameter1().equals(m2.getParameter1()) || m1.getParameter2().equals(m2.getParameter2())) { + final FunctionOperator m1 = (FunctionOperator) fnc.getParameter1(); + final FunctionOperator m2 = (FunctionOperator) fnc.getParameter2(); + if (m1.getParameter1().equals(m2.getParameter1()) || m1.getParameter2().equals(m2.getParameter2())) isExecutable = true; - } } } if (isExecutable) { - FunctionOperator fnc = (FunctionOperator) f; - MathContext root = fnc.getMathContext(); - ObjectArrayList result = new ObjectArrayList<>(); - FunctionOperator m1 = (FunctionOperator) fnc.getParameter1(); - FunctionOperator m2 = (FunctionOperator) fnc.getParameter2(); + final FunctionOperator fnc = (FunctionOperator) f; + final MathContext root = fnc.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); + final FunctionOperator m1 = (FunctionOperator) fnc.getParameter1(); + final FunctionOperator m2 = (FunctionOperator) fnc.getParameter2(); Function a; Function b; Function x; @@ -74,16 +73,14 @@ public class VariableRule1 implements Rule { } Function rets; - if (fnc instanceof Sum) { + if (fnc instanceof Sum) rets = new Sum(root, a, b); - } else { + else rets = new Subtraction(root, a, b); - } - Function retm = new Multiplication(root, rets, x); + final Function retm = new Multiplication(root, rets, x); result.add(retm); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/VariableRule2.java b/rules/src/main/java/rules/VariableRule2.java index 422b1e7c..4bc2a276 100644 --- a/rules/src/main/java/rules/VariableRule2.java +++ b/rules/src/main/java/rules/VariableRule2.java @@ -18,7 +18,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Variable rule * ax+x=(a+1)*x (a,b NUMBER; x VARIABLES) - * + * * @author Andrea Cavalli * */ @@ -42,37 +42,34 @@ public class VariableRule2 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Sum || f instanceof Subtraction) { - FunctionOperator fnc = (FunctionOperator) f; + final FunctionOperator fnc = (FunctionOperator) f; if (fnc.getParameter1() instanceof Multiplication) { - FunctionOperator m1 = (FunctionOperator) fnc.getParameter1(); - if (m1.getParameter2().equals(fnc.getParameter2())) { + final FunctionOperator m1 = (FunctionOperator) fnc.getParameter1(); + if (m1.getParameter2().equals(fnc.getParameter2())) isExecutable = true; - } } } if (isExecutable) { - FunctionOperator fnc = (FunctionOperator) f; - MathContext root = fnc.getMathContext(); - ObjectArrayList result = new ObjectArrayList<>(); - FunctionOperator m1 = (FunctionOperator) fnc.getParameter1(); - Function a = m1.getParameter1(); - Function x = fnc.getParameter2(); + final FunctionOperator fnc = (FunctionOperator) f; + final MathContext root = fnc.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); + final FunctionOperator m1 = (FunctionOperator) fnc.getParameter1(); + final Function a = m1.getParameter1(); + final Function x = fnc.getParameter2(); Function rets; - if (fnc instanceof Sum) { + if (fnc instanceof Sum) rets = new Sum(root, a, new Number(root, 1)); - } else { + else rets = new Subtraction(root, a, new Number(root, 1)); - } - Function retm = new Multiplication(root, rets, x); + final Function retm = new Multiplication(root, rets, x); result.add(retm); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/VariableRule3.java b/rules/src/main/java/rules/VariableRule3.java index 723dabe1..82a0d6fb 100644 --- a/rules/src/main/java/rules/VariableRule3.java +++ b/rules/src/main/java/rules/VariableRule3.java @@ -18,7 +18,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Variable rule * x+ax=(a+1)*x (a,b NUMBER; x VARIABLES) - * + * * @author Andrea Cavalli * */ @@ -42,38 +42,35 @@ public class VariableRule3 implements Rule { */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { boolean isExecutable = false; if (f instanceof Sum || f instanceof Subtraction) { - FunctionOperator fnc = (FunctionOperator) f; + final FunctionOperator fnc = (FunctionOperator) f; if (fnc.getParameter2() instanceof Multiplication) { - FunctionOperator m2 = (FunctionOperator) fnc.getParameter2(); - if (m2.getParameter2().equals(fnc.getParameter1())) { + final FunctionOperator m2 = (FunctionOperator) fnc.getParameter2(); + if (m2.getParameter2().equals(fnc.getParameter1())) isExecutable = true; - } } } if (isExecutable) { - FunctionOperator fnc = (FunctionOperator) f; - MathContext root = fnc.getMathContext(); - ObjectArrayList result = new ObjectArrayList<>(); - FunctionOperator m2 = (FunctionOperator) fnc.getParameter2(); - Function a = m2.getParameter1(); - Function x = fnc.getParameter1(); + final FunctionOperator fnc = (FunctionOperator) f; + final MathContext root = fnc.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); + final FunctionOperator m2 = (FunctionOperator) fnc.getParameter2(); + final Function a = m2.getParameter1(); + final Function x = fnc.getParameter1(); Function rets; - if (fnc instanceof Sum) { + if (fnc instanceof Sum) rets = new Sum(root, new Number(root, 1), a); - } else { + else rets = new Subtraction(root, new Number(root, 1), a); - } - Function retm = new Multiplication(root, rets, x); + final Function retm = new Multiplication(root, rets, x); result.add(retm); return result; - } else { + } else return null; - } } } diff --git a/rules/src/main/java/rules/functions/DivisionRule.java b/rules/src/main/java/rules/functions/DivisionRule.java index 5ef9b6d3..c1935f06 100644 --- a/rules/src/main/java/rules/functions/DivisionRule.java +++ b/rules/src/main/java/rules/functions/DivisionRule.java @@ -21,7 +21,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Division * a/b = c - * + * * @author Andrea Cavalli * */ @@ -44,13 +44,13 @@ public class DivisionRule implements Rule { - An ObjectArrayList if it did something */ @Override - public ObjectArrayList execute(Function f) throws Error { + public ObjectArrayList execute(final Function f) throws Error { if (f instanceof Division) { - ObjectArrayList result = new ObjectArrayList<>(); - Function variable1 = ((FunctionOperator) f).getParameter1(); - Function variable2 = ((FunctionOperator) f).getParameter2(); - MathContext mathContext = f.getMathContext(); - if (variable1 instanceof Number && variable2 instanceof Number) { + final ObjectArrayList result = new ObjectArrayList<>(); + final Function variable1 = ((FunctionOperator) f).getParameter1(); + final Function variable2 = ((FunctionOperator) f).getParameter2(); + final MathContext mathContext = f.getMathContext(); + if (variable1 instanceof Number && variable2 instanceof Number) if (mathContext.exactMode) { if (((Number) variable1).isInteger() && ((Number) variable2).isInteger()) { LinkedList factors1, factors2, mcm; @@ -58,14 +58,14 @@ public class DivisionRule implements Rule { factors1 = ((Number) variable1).getFactors(); factors2 = ((Number) variable2).getFactors(); mcm = ScriptUtils.mcm(factors1, factors2); - } catch (Exception ex) { + } catch (final Exception ex) { return null; } if (mcm.size() > 0) { //true if there is at least one common factor //divide by the common factor (ab/cb = a/c) BigInteger nmb1 = ((Number) variable1).getTerm().toBigIntegerExact(); BigInteger nmb2 = ((Number) variable2).getTerm().toBigIntegerExact(); - for (BigInteger integerNumber : mcm) { + for (final BigInteger integerNumber : mcm) { nmb1 = nmb1.divide(integerNumber); nmb2 = nmb2.divide(integerNumber); } @@ -78,7 +78,6 @@ public class DivisionRule implements Rule { result.add(((Number) variable1).divide((Number) variable2)); return result; } - } } return null; } diff --git a/rules/src/main/java/rules/functions/EmptyNumberRule.java b/rules/src/main/java/rules/functions/EmptyNumberRule.java index bee37cfd..02be7d93 100644 --- a/rules/src/main/java/rules/functions/EmptyNumberRule.java +++ b/rules/src/main/java/rules/functions/EmptyNumberRule.java @@ -12,7 +12,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * EmptyNumber * - * + * * @author Andrea Cavalli * */ @@ -35,7 +35,7 @@ public class EmptyNumberRule implements Rule { - An ObjectArrayList if it did something */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { return null; } } diff --git a/rules/src/main/java/rules/functions/ExpressionRule.java b/rules/src/main/java/rules/functions/ExpressionRule.java index 680b8847..4edab81a 100644 --- a/rules/src/main/java/rules/functions/ExpressionRule.java +++ b/rules/src/main/java/rules/functions/ExpressionRule.java @@ -13,7 +13,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Expression * (x) = x - * + * * @author Andrea Cavalli * */ @@ -36,9 +36,9 @@ public class ExpressionRule implements Rule { - An ObjectArrayList if it did something */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { if (f instanceof Expression) { - ObjectArrayList result = new ObjectArrayList<>(); + final ObjectArrayList result = new ObjectArrayList<>(); result.add(f.getParameter(0)); return result; } diff --git a/rules/src/main/java/rules/functions/JokeRule.java b/rules/src/main/java/rules/functions/JokeRule.java index 2afe7a9a..6c3592c0 100644 --- a/rules/src/main/java/rules/functions/JokeRule.java +++ b/rules/src/main/java/rules/functions/JokeRule.java @@ -12,7 +12,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Joke * - * + * * @author Andrea Cavalli * */ @@ -35,7 +35,7 @@ public class JokeRule implements Rule { - An ObjectArrayList if it did something */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { return null; } } diff --git a/rules/src/main/java/rules/functions/MultiplicationRule.java b/rules/src/main/java/rules/functions/MultiplicationRule.java index 93df1fb7..631b14e4 100644 --- a/rules/src/main/java/rules/functions/MultiplicationRule.java +++ b/rules/src/main/java/rules/functions/MultiplicationRule.java @@ -5,7 +5,6 @@ SETTINGS: (please don't move this part) */ import it.cavallium.warppi.math.Function; -import it.cavallium.warppi.math.MathContext; import it.cavallium.warppi.math.functions.Multiplication; import it.cavallium.warppi.math.functions.Number; import it.cavallium.warppi.math.rules.Rule; @@ -15,7 +14,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Multiplication * a*b = c - * + * * @author Andrea Cavalli * */ @@ -38,12 +37,11 @@ public class MultiplicationRule implements Rule { - An ObjectArrayList if it did something */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { if (f instanceof Multiplication) { - ObjectArrayList result = new ObjectArrayList<>(); - Function variable1 = ((Multiplication) f).getParameter1(); - Function variable2 = ((Multiplication) f).getParameter2(); - MathContext mathContext = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); + final Function variable1 = ((Multiplication) f).getParameter1(); + final Function variable2 = ((Multiplication) f).getParameter2(); if (variable1 instanceof Number && variable2 instanceof Number) { //multiply a by b (a*b = c) result.add(((Number) variable1).multiply((Number) variable2)); diff --git a/rules/src/main/java/rules/functions/NegativeRule.java b/rules/src/main/java/rules/functions/NegativeRule.java index b9057740..8bdc9e5c 100644 --- a/rules/src/main/java/rules/functions/NegativeRule.java +++ b/rules/src/main/java/rules/functions/NegativeRule.java @@ -17,7 +17,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Negative * -a = b - * + * * @author Andrea Cavalli * */ @@ -40,23 +40,22 @@ public class NegativeRule implements Rule { - An ObjectArrayList if it did something */ @Override - public ObjectArrayList execute(Function f) throws Error { + public ObjectArrayList execute(final Function f) throws Error { if (f instanceof Negative) { - ObjectArrayList result = new ObjectArrayList<>(); - Function variable = ((Negative) f).getParameter(); - MathContext mathContext = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); + final Function variable = ((Negative) f).getParameter(); + final MathContext mathContext = f.getMathContext(); if (variable instanceof Number) { //-a = a*-1 = b try { result.add(((Number) variable).multiply(new Number(mathContext, -1))); - } catch (Exception ex) { - if (ex instanceof NullPointerException) { + } catch (final Exception ex) { + if (ex instanceof NullPointerException) throw new Error(Errors.ERROR); - } else if (ex instanceof NumberFormatException) { + else if (ex instanceof NumberFormatException) throw new Error(Errors.SYNTAX_ERROR); - } else if (ex instanceof ArithmeticException) { + else if (ex instanceof ArithmeticException) throw new Error(Errors.NUMBER_TOO_SMALL); - } } return result; } diff --git a/rules/src/main/java/rules/functions/NumberRule.java b/rules/src/main/java/rules/functions/NumberRule.java index 7d407891..12af8253 100644 --- a/rules/src/main/java/rules/functions/NumberRule.java +++ b/rules/src/main/java/rules/functions/NumberRule.java @@ -17,7 +17,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Number * - * + * * @author Andrea Cavalli * */ @@ -40,19 +40,18 @@ public class NumberRule implements Rule { - An ObjectArrayList if it did something */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { if (f instanceof Number) { - ObjectArrayList result = new ObjectArrayList<>(); - MathContext mathContext = f.getMathContext(); - if (mathContext.exactMode) { + final ObjectArrayList result = new ObjectArrayList<>(); + final MathContext mathContext = f.getMathContext(); + if (mathContext.exactMode) if (((Number) f).isInteger() == false) { - Number divisor = new Number(mathContext, BigInteger.TEN.pow(((Number) f).getNumberOfDecimalPlaces())); - Function number = new Number(mathContext, ((Number) f).getTerm().multiply(divisor.getTerm())); - Function div = new Division(mathContext, number, divisor); + final Number divisor = new Number(mathContext, BigInteger.TEN.pow(((Number) f).getNumberOfDecimalPlaces())); + final Function number = new Number(mathContext, ((Number) f).getTerm().multiply(divisor.getTerm())); + final Function div = new Division(mathContext, number, divisor); result.add(div); return result; } - } } return null; } diff --git a/rules/src/main/java/rules/functions/PowerRule.java b/rules/src/main/java/rules/functions/PowerRule.java index cfc46004..46cec6c4 100644 --- a/rules/src/main/java/rules/functions/PowerRule.java +++ b/rules/src/main/java/rules/functions/PowerRule.java @@ -16,7 +16,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Power * a^b = c - * + * * @author Andrea Cavalli * */ @@ -39,18 +39,18 @@ public class PowerRule implements Rule { - An ObjectArrayList if it did something */ @Override - public ObjectArrayList execute(Function f) throws it.cavallium.warppi.util.Error, InterruptedException { + public ObjectArrayList execute(final Function f) + throws it.cavallium.warppi.util.Error, InterruptedException { if (f instanceof Power) { - ObjectArrayList result = new ObjectArrayList<>(); - Function variable1 = ((FunctionOperator) f).getParameter1(); - Function variable2 = ((FunctionOperator) f).getParameter2(); - MathContext mathContext = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); + final Function variable1 = ((FunctionOperator) f).getParameter1(); + final Function variable2 = ((FunctionOperator) f).getParameter2(); + final MathContext mathContext = f.getMathContext(); if (variable1 instanceof Number && variable2 instanceof Number) { //a^b = c - Number out = ((Number) variable1).pow((Number) variable2); - if (mathContext.exactMode && !out.isInteger()) { + final Number out = ((Number) variable1).pow((Number) variable2); + if (mathContext.exactMode && !out.isInteger()) return null; - } result.add(out); return result; } diff --git a/rules/src/main/java/rules/functions/RootRule.java b/rules/src/main/java/rules/functions/RootRule.java index c5efc9de..a824828f 100644 --- a/rules/src/main/java/rules/functions/RootRule.java +++ b/rules/src/main/java/rules/functions/RootRule.java @@ -22,7 +22,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Root * a√b = c - * + * * @author Andrea Cavalli * */ @@ -45,43 +45,39 @@ public class RootRule implements Rule { - An ObjectArrayList if it did something */ @Override - public ObjectArrayList execute(Function f) throws Error, InterruptedException { + public ObjectArrayList execute(final Function f) throws Error, InterruptedException { boolean isSquare = false; if ((isSquare = f instanceof RootSquare) || f instanceof Root) { - ObjectArrayList result = new ObjectArrayList<>(); - MathContext mathContext = f.getMathContext(); - Function variable1 = ((FunctionOperator) f).getParameter1(); - Function variable2 = ((FunctionOperator) f).getParameter2(); + final ObjectArrayList result = new ObjectArrayList<>(); + final MathContext mathContext = f.getMathContext(); + final Function variable1 = ((FunctionOperator) f).getParameter1(); + final Function variable2 = ((FunctionOperator) f).getParameter2(); boolean isSolvable = false, canBePorted = false; if (variable1 instanceof Number && variable2 instanceof Number) { if (mathContext.exactMode) { - result.add(((Number) variable1).pow(new Number(mathContext, BigDecimal.ONE).divide(((Number) variable1)))); + result.add(((Number) variable1).pow(new Number(mathContext, BigDecimal.ONE).divide((Number) variable1))); return result; } isSolvable = isSolvable | !mathContext.exactMode; - if (!isSolvable) { + if (!isSolvable) try { - Function resultVar = ((Number) variable2).pow(new Number(mathContext, BigDecimal.ONE).divide(((Number) variable1))); - Function originalVariable = ((Number) resultVar).pow(new Number(mathContext, 2)); - if ((originalVariable).equals(((FunctionOperator) f).getParameter2())) { + final Function resultVar = ((Number) variable2).pow(new Number(mathContext, BigDecimal.ONE).divide((Number) variable1)); + final Function originalVariable = ((Number) resultVar).pow(new Number(mathContext, 2)); + if (originalVariable.equals(((FunctionOperator) f).getParameter2())) isSolvable = true; - } - } catch (Exception ex) { + } catch (final Exception ex) { throw (Error) new Error(Errors.ERROR, ex.getMessage()).initCause(ex); } - } } - if (!isSquare && !isSolvable && variable1 instanceof Number && variable1.equals(new Number(mathContext, 2))) { + if (!isSquare && !isSolvable && variable1 instanceof Number && variable1.equals(new Number(mathContext, 2))) canBePorted = true; - } if (isSolvable) { result.add(((Number) variable2).pow(new Number(mathContext, BigInteger.ONE).divide((Number) variable1))); return result; } - if (canBePorted) { + if (canBePorted) result.add(new RootSquare(mathContext, variable2)); - } } return null; } diff --git a/rules/src/main/java/rules/functions/SubtractionRule.java b/rules/src/main/java/rules/functions/SubtractionRule.java index 674c376d..3ccb3bdb 100644 --- a/rules/src/main/java/rules/functions/SubtractionRule.java +++ b/rules/src/main/java/rules/functions/SubtractionRule.java @@ -16,7 +16,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Subtraction * a-b = c - * + * * @author Andrea Cavalli * */ @@ -39,12 +39,12 @@ public class SubtractionRule implements Rule { - An ObjectArrayList if it did something */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { if (f instanceof Subtraction) { - ObjectArrayList result = new ObjectArrayList<>(); - Function variable1 = ((FunctionOperator) f).getParameter1(); - Function variable2 = ((FunctionOperator) f).getParameter2(); - MathContext mathContext = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); + final Function variable1 = ((FunctionOperator) f).getParameter1(); + final Function variable2 = ((FunctionOperator) f).getParameter2(); + final MathContext mathContext = f.getMathContext(); if (variable1 instanceof Number && variable2 instanceof Number) { //a-b = a+(b*-1) = c result.add(((Number) variable1).add(((Number) variable2).multiply(new Number(mathContext, -1)))); diff --git a/rules/src/main/java/rules/functions/SumRule.java b/rules/src/main/java/rules/functions/SumRule.java index 429f4136..ebe2d7a3 100644 --- a/rules/src/main/java/rules/functions/SumRule.java +++ b/rules/src/main/java/rules/functions/SumRule.java @@ -6,7 +6,6 @@ SETTINGS: (please don't move this part) import it.cavallium.warppi.math.Function; import it.cavallium.warppi.math.FunctionOperator; -import it.cavallium.warppi.math.MathContext; import it.cavallium.warppi.math.functions.Number; import it.cavallium.warppi.math.functions.Sum; import it.cavallium.warppi.math.rules.Rule; @@ -16,7 +15,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Sum * a+b = c - * + * * @author Andrea Cavalli * */ @@ -39,15 +38,14 @@ public class SumRule implements Rule { - An ObjectArrayList if it did something */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { if (f instanceof Sum) { - ObjectArrayList result = new ObjectArrayList<>(); - Function variable1 = ((FunctionOperator) f).getParameter1(); - Function variable2 = ((FunctionOperator) f).getParameter2(); - MathContext mathContext = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); + final Function variable1 = ((FunctionOperator) f).getParameter1(); + final Function variable2 = ((FunctionOperator) f).getParameter2(); if (variable1 instanceof Number && variable2 instanceof Number) { //a+b = c - result.add(((Number) variable1).add(((Number) variable2))); + result.add(((Number) variable1).add((Number) variable2)); return result; } } diff --git a/rules/src/main/java/rules/functions/SumSubtractionRule.java b/rules/src/main/java/rules/functions/SumSubtractionRule.java index b206c342..ac1ea246 100644 --- a/rules/src/main/java/rules/functions/SumSubtractionRule.java +++ b/rules/src/main/java/rules/functions/SumSubtractionRule.java @@ -16,7 +16,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * SumSumbraction * a±b = c, d - * + * * @author Andrea Cavalli * */ @@ -39,12 +39,12 @@ public class SumSubtractionRule implements Rule { - An ObjectArrayList if it did something */ @Override - public ObjectArrayList execute(Function f) { + public ObjectArrayList execute(final Function f) { if (f instanceof SumSubtraction) { - ObjectArrayList result = new ObjectArrayList<>(); - Function variable1 = ((FunctionOperator) f).getParameter1(); - Function variable2 = ((FunctionOperator) f).getParameter2(); - MathContext mathContext = f.getMathContext(); + final ObjectArrayList result = new ObjectArrayList<>(); + final Function variable1 = ((FunctionOperator) f).getParameter1(); + final Function variable2 = ((FunctionOperator) f).getParameter2(); + final MathContext mathContext = f.getMathContext(); if (variable1 instanceof Number && variable2 instanceof Number) { //a±b = c, d result.add(((Number) variable1).add((Number) variable2)); diff --git a/rules/src/main/java/rules/functions/VariableRule.java b/rules/src/main/java/rules/functions/VariableRule.java index b102fc3a..3823f125 100644 --- a/rules/src/main/java/rules/functions/VariableRule.java +++ b/rules/src/main/java/rules/functions/VariableRule.java @@ -20,7 +20,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; /** * Variable * a = n - * + * * @author Andrea Cavalli * */ @@ -43,18 +43,17 @@ public class VariableRule implements Rule { - An ObjectArrayList if it did something */ @Override - public ObjectArrayList execute(Function f) throws Error { + public ObjectArrayList execute(final Function f) throws Error { if (f instanceof Variable) { - ObjectArrayList result = new ObjectArrayList<>(); - Character variable = ((Variable) f).getChar(); - MathContext mathContext = f.getMathContext(); - if (mathContext.exactMode == false) { + final ObjectArrayList result = new ObjectArrayList<>(); + final Character variable = ((Variable) f).getChar(); + final MathContext mathContext = f.getMathContext(); + if (mathContext.exactMode == false) if (variable.equals(MathematicalSymbols.PI)) { //a = n result.add(new Number(mathContext, BigDecimalMath.pi(new java.math.MathContext(Utils.scale, Utils.scaleMode2)))); return result; } - } } return null; } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/BufferedStreamFeeder.java b/teavm/src/main/java/ar/com/hjg/pngj/BufferedStreamFeeder.java index ef93efc9..1b2b548b 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/BufferedStreamFeeder.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/BufferedStreamFeeder.java @@ -8,192 +8,201 @@ import java.io.InputStream; */ public class BufferedStreamFeeder { - private InputStream stream; - private byte[] buf; - private int pendinglen; // bytes read and stored in buf that have not yet still been fed to - // IBytesConsumer - private int offset; - private boolean eof = false; - private boolean closeStream = true; - private boolean failIfNoFeed = false; + private InputStream stream; + private byte[] buf; + private int pendinglen; // bytes read and stored in buf that have not yet still been fed to + // IBytesConsumer + private int offset; + private boolean eof = false; + private boolean closeStream = true; + private boolean failIfNoFeed = false; - private static final int DEFAULTSIZE = 8192; + private static final int DEFAULTSIZE = 8192; - /** By default, the stream will be closed on close() */ - public BufferedStreamFeeder(InputStream is) { - this(is, DEFAULTSIZE); - } + /** By default, the stream will be closed on close() */ + public BufferedStreamFeeder(final InputStream is) { + this(is, BufferedStreamFeeder.DEFAULTSIZE); + } - public BufferedStreamFeeder(InputStream is, int bufsize) { - this.stream = is; - buf = new byte[bufsize < 1 ? DEFAULTSIZE : bufsize]; - } + public BufferedStreamFeeder(final InputStream is, final int bufsize) { + stream = is; + buf = new byte[bufsize < 1 ? BufferedStreamFeeder.DEFAULTSIZE : bufsize]; + } - /** - * Returns inputstream - * - * @return Input Stream from which bytes are read - */ - public InputStream getStream() { - return stream; - } + /** + * Returns inputstream + * + * @return Input Stream from which bytes are read + */ + public InputStream getStream() { + return stream; + } - /** - * Feeds bytes to the consumer
- * Returns bytes actually consumed
- * This should return 0 only if the stream is EOF or the consumer is done - */ - public int feed(IBytesConsumer consumer) { - return feed(consumer, Integer.MAX_VALUE); - } + /** + * Feeds bytes to the consumer
+ * Returns bytes actually consumed
+ * This should return 0 only if the stream is EOF or the consumer is done + */ + public int feed(final IBytesConsumer consumer) { + return feed(consumer, Integer.MAX_VALUE); + } - /** - * Feeds the consumer (with at most maxbytes)
- * Returns 0 only if the stream is EOF (or maxbytes=0). Returns negative is the consumer is done.
- * It can return less than maxbytes (that doesn't mean that the consumer or the input stream is done) - */ - public int feed(IBytesConsumer consumer, int maxbytes) { - if (pendinglen == 0) - refillBuffer(); - int tofeed = maxbytes >= 0 && maxbytes < pendinglen ? maxbytes : pendinglen; - int n = 0; - if (tofeed > 0) { - n = consumer.consume(buf, offset, tofeed); - if (n > 0) { - offset += n; - pendinglen -= n; - } - } - if (n < 1 && failIfNoFeed) - throw new PngjInputException("Failed to feed bytes (premature ending?)"); - return n; - } + /** + * Feeds the consumer (with at most maxbytes)
+ * Returns 0 only if the stream is EOF (or maxbytes=0). Returns negative is + * the consumer is done.
+ * It can return less than maxbytes (that doesn't mean that the consumer or + * the input stream is done) + */ + public int feed(final IBytesConsumer consumer, final int maxbytes) { + if (pendinglen == 0) + refillBuffer(); + final int tofeed = maxbytes >= 0 && maxbytes < pendinglen ? maxbytes : pendinglen; + int n = 0; + if (tofeed > 0) { + n = consumer.consume(buf, offset, tofeed); + if (n > 0) { + offset += n; + pendinglen -= n; + } + } + if (n < 1 && failIfNoFeed) + throw new PngjInputException("Failed to feed bytes (premature ending?)"); + return n; + } + /** + * Feeds as much bytes as it can to the consumer, in a loop.
+ * Returns bytes actually consumed
+ * This will stop when either the input stream is eof, or when the consumer + * refuses to eat more bytes. The caller can + * distinguish both cases by calling {@link #hasMoreToFeed()} + */ + public long feedAll(final IBytesConsumer consumer) { + long n = 0; + while (hasMoreToFeed()) { + final int n1 = feed(consumer); + if (n1 < 1) + break; + n += n1; + } + return n; + } - /** - * Feeds as much bytes as it can to the consumer, in a loop.
- * Returns bytes actually consumed
- * This will stop when either the input stream is eof, or when the consumer refuses to eat more bytes. The caller can - * distinguish both cases by calling {@link #hasMoreToFeed()} - */ - public long feedAll(IBytesConsumer consumer) { - long n = 0; - while (hasMoreToFeed()) { - int n1 = feed(consumer); - if (n1 < 1) - break; - n += n1; - } - return n; - } + /** + * Feeds exactly nbytes, retrying if necessary + * + * @param consumer + * Consumer + * @param nbytes + * Number of bytes + * @return true if success, false otherwise (EOF on stream, or consumer is + * done) + */ + public boolean feedFixed(final IBytesConsumer consumer, final int nbytes) { + int remain = nbytes; + while (remain > 0) { + final int n = feed(consumer, remain); + if (n < 1) + return false; + remain -= n; + } + return true; + } + /** + * If there are not pending bytes to be consumed tries to fill the buffer + * with bytes from the stream. + */ + protected void refillBuffer() { + if (pendinglen > 0 || eof) + return; // only if not pending data + try { + // try to read + offset = 0; + pendinglen = stream.read(buf); + if (pendinglen < 0) { + close(); + return; + } else + return; + } catch (final IOException e) { + throw new PngjInputException(e); + } + } - /** - * Feeds exactly nbytes, retrying if necessary - * - * @param consumer Consumer - * @param nbytes Number of bytes - * @return true if success, false otherwise (EOF on stream, or consumer is done) - */ - public boolean feedFixed(IBytesConsumer consumer, int nbytes) { - int remain = nbytes; - while (remain > 0) { - int n = feed(consumer, remain); - if (n < 1) - return false; - remain -= n; - } - return true; - } + /** + * Returuns true if we have more data to fed the consumer. This internally + * tries to grabs more bytes from the stream + * if necessary + */ + public boolean hasMoreToFeed() { + if (eof) + return pendinglen > 0; + else + refillBuffer(); + return pendinglen > 0; + } - /** - * If there are not pending bytes to be consumed tries to fill the buffer with bytes from the stream. - */ - protected void refillBuffer() { - if (pendinglen > 0 || eof) - return; // only if not pending data - try { - // try to read - offset = 0; - pendinglen = stream.read(buf); - if (pendinglen < 0) { - close(); - return; - } else - return; - } catch (IOException e) { - throw new PngjInputException(e); - } - } + /** + * @param closeStream + * If true, the underlying stream will be closed on when close() + * is called + */ + public void setCloseStream(final boolean closeStream) { + this.closeStream = closeStream; + } - /** - * Returuns true if we have more data to fed the consumer. This internally tries to grabs more bytes from the stream - * if necessary - */ - public boolean hasMoreToFeed() { - if (eof) - return pendinglen > 0; - else - refillBuffer(); - return pendinglen > 0; - } + /** + * Closes this object. + * + * Sets EOF=true, and closes the stream if closeStream is true + * + * This can be called internally, or from outside. + * + * Idempotent, secure, never throws exception. + **/ + public void close() { + eof = true; + buf = null; + pendinglen = 0; + offset = 0; + if (stream != null && closeStream) + try { + stream.close(); + } catch (final Exception e) { + // PngHelperInternal.LOGGER.log(Level.WARNING, "Exception closing stream", e); + } + stream = null; + } - /** - * @param closeStream If true, the underlying stream will be closed on when close() is called - */ - public void setCloseStream(boolean closeStream) { - this.closeStream = closeStream; - } + /** + * Sets a new underlying inputstream. This allows to reuse this object. The + * old underlying is not closed and the state + * is not reset (you should call close() previously if you want that) + * + * @param is + */ + public void setInputStream(final InputStream is) { // to reuse this object + stream = is; + eof = false; + } - /** - * Closes this object. - * - * Sets EOF=true, and closes the stream if closeStream is true - * - * This can be called internally, or from outside. - * - * Idempotent, secure, never throws exception. - **/ - public void close() { - eof = true; - buf = null; - pendinglen = 0; - offset = 0; - if (stream != null && closeStream) { - try { - stream.close(); - } catch (Exception e) { - // PngHelperInternal.LOGGER.log(Level.WARNING, "Exception closing stream", e); - } - } - stream = null; - } + /** + * @return EOF on stream, or close() was called + */ + public boolean isEof() { + return eof; + } - /** - * Sets a new underlying inputstream. This allows to reuse this object. The old underlying is not closed and the state - * is not reset (you should call close() previously if you want that) - * - * @param is - */ - public void setInputStream(InputStream is) { // to reuse this object - this.stream = is; - eof = false; - } - - /** - * @return EOF on stream, or close() was called - */ - public boolean isEof() { - return eof; - } - - /** - * If this flag is set (default: false), any call to feed() that returns zero (no byte feed) will throw an exception. - * This is useful to be sure of avoid infinite loops in some scenarios. - * - * @param failIfNoFeed - */ - public void setFailIfNoFeed(boolean failIfNoFeed) { - this.failIfNoFeed = failIfNoFeed; - } + /** + * If this flag is set (default: false), any call to feed() that returns + * zero (no byte feed) will throw an exception. + * This is useful to be sure of avoid infinite loops in some scenarios. + * + * @param failIfNoFeed + */ + public void setFailIfNoFeed(final boolean failIfNoFeed) { + this.failIfNoFeed = failIfNoFeed; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/ChunkReader.java b/teavm/src/main/java/ar/com/hjg/pngj/ChunkReader.java index 4c045853..a33934bb 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/ChunkReader.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/ChunkReader.java @@ -3,214 +3,229 @@ package ar.com.hjg.pngj; import ar.com.hjg.pngj.chunks.ChunkRaw; /** - * Parses a PNG chunk, consuming bytes in one mode: {@link ChunkReaderMode#BUFFER}, {@link ChunkReaderMode#PROCESS}, + * Parses a PNG chunk, consuming bytes in one mode: + * {@link ChunkReaderMode#BUFFER}, {@link ChunkReaderMode#PROCESS}, * {@link ChunkReaderMode#SKIP}. *

- * It calls {@link #chunkDone()} when done. Also calls {@link #processData(byte[], int, int)} if PROCESS - * mode. Apart from thas, it's totally agnostic (it doesn't know about IDAT chunks, or PNG general structure) + * It calls {@link #chunkDone()} when done. Also calls + * {@link #processData(byte[], int, int)} if PROCESS + * mode. Apart from thas, it's totally agnostic (it doesn't know about IDAT + * chunks, or PNG general structure) *

- * The object wraps a ChunkRaw instance (content filled only if BUFFER mode); it should be short lived (one instance - * created for each chunk, and discarded after reading), but the wrapped chunkRaw can be (usually is) long lived. + * The object wraps a ChunkRaw instance (content filled only if BUFFER mode); it + * should be short lived (one instance + * created for each chunk, and discarded after reading), but the wrapped + * chunkRaw can be (usually is) long lived. */ public abstract class ChunkReader { - /** - * see {@link ChunkReaderMode} - */ - public final ChunkReaderMode mode; - private final ChunkRaw chunkRaw; + /** + * see {@link ChunkReaderMode} + */ + public final ChunkReaderMode mode; + private final ChunkRaw chunkRaw; - private boolean crcCheck; // by default, this is false for SKIP, true elsewhere + private boolean crcCheck; // by default, this is false for SKIP, true elsewhere - /** - * How many bytes have been read for this chunk, data only - */ - protected int read = 0; - private int crcn = 0; // how many bytes have been read from crc + /** + * How many bytes have been read for this chunk, data only + */ + protected int read = 0; + private int crcn = 0; // how many bytes have been read from crc - /** - * Modes of ChunkReader chunk processing. - */ - public enum ChunkReaderMode { - /** - * Stores full chunk data in buffer - */ - BUFFER, - /** - * Does not store content, processes on the fly, calling processData() for each partial read - */ - PROCESS, - /** - * Does not store nor process - implies crcCheck=false (by default). - */ - SKIP; - } + /** + * Modes of ChunkReader chunk processing. + */ + public enum ChunkReaderMode { + /** + * Stores full chunk data in buffer + */ + BUFFER, + /** + * Does not store content, processes on the fly, calling processData() + * for each partial read + */ + PROCESS, + /** + * Does not store nor process - implies crcCheck=false (by default). + */ + SKIP; + } - /** - * The constructor creates also a chunkRaw, preallocated if mode = ChunkReaderMode.BUFFER - * - * @param clen - * @param id - * @param offsetInPng Informational, is stored in chunkRaw - * @param mode - */ - public ChunkReader(int clen, String id, long offsetInPng, ChunkReaderMode mode) { - if (mode == null || id.length() != 4 || clen < 0) - throw new PngjExceptionInternal("Bad chunk paramenters: " + mode); - this.mode = mode; - chunkRaw = new ChunkRaw(clen, id, mode == ChunkReaderMode.BUFFER); - chunkRaw.setOffset(offsetInPng); - this.crcCheck = mode == ChunkReaderMode.SKIP ? false : true; // can be changed with setter - } + /** + * The constructor creates also a chunkRaw, preallocated if mode = + * ChunkReaderMode.BUFFER + * + * @param clen + * @param id + * @param offsetInPng + * Informational, is stored in chunkRaw + * @param mode + */ + public ChunkReader(final int clen, final String id, final long offsetInPng, final ChunkReaderMode mode) { + if (mode == null || id.length() != 4 || clen < 0) + throw new PngjExceptionInternal("Bad chunk paramenters: " + mode); + this.mode = mode; + chunkRaw = new ChunkRaw(clen, id, mode == ChunkReaderMode.BUFFER); + chunkRaw.setOffset(offsetInPng); + crcCheck = mode == ChunkReaderMode.SKIP ? false : true; // can be changed with setter + } - /** - * Returns raw chunk (data can be empty or not, depending on ChunkReaderMode) - * - * @return Raw chunk - never null - */ - public ChunkRaw getChunkRaw() { - return chunkRaw; - } + /** + * Returns raw chunk (data can be empty or not, depending on + * ChunkReaderMode) + * + * @return Raw chunk - never null + */ + public ChunkRaw getChunkRaw() { + return chunkRaw; + } - /** - * Consumes data for the chunk (data and CRC). This never consumes more bytes than for this chunk. - * - * In HOT_PROCESS can call processData() (not more than once) - * - * If this ends the chunk (included CRC) it checks CRC (if checking) and calls chunkDone() - * - * @param buf - * @param off - * @param len - * @return How many bytes have been consumed - */ - public final int feedBytes(byte[] buf, int off, int len) { - if (len == 0) - return 0; - if (len < 0) - throw new PngjException("negative length??"); - if (read == 0 && crcn == 0 && crcCheck) - chunkRaw.updateCrc(chunkRaw.idbytes, 0, 4); // initializes crc calculation with the Chunk ID - int bytesForData = chunkRaw.len - read; // bytesForData : bytes to be actually read from chunk data - if (bytesForData > len) - bytesForData = len; - // we want to call processData even for empty chunks (IEND:bytesForData=0) at least once - if (bytesForData > 0 || crcn == 0) { - // in buffer mode we compute the CRC at the end - if (crcCheck && mode != ChunkReaderMode.BUFFER && bytesForData > 0) - chunkRaw.updateCrc(buf, off, bytesForData); + /** + * Consumes data for the chunk (data and CRC). This never consumes more + * bytes than for this chunk. + * + * In HOT_PROCESS can call processData() (not more than once) + * + * If this ends the chunk (included CRC) it checks CRC (if checking) and + * calls chunkDone() + * + * @param buf + * @param off + * @param len + * @return How many bytes have been consumed + */ + public final int feedBytes(final byte[] buf, int off, int len) { + if (len == 0) + return 0; + if (len < 0) + throw new PngjException("negative length??"); + if (read == 0 && crcn == 0 && crcCheck) + chunkRaw.updateCrc(chunkRaw.idbytes, 0, 4); // initializes crc calculation with the Chunk ID + int bytesForData = chunkRaw.len - read; // bytesForData : bytes to be actually read from chunk data + if (bytesForData > len) + bytesForData = len; + // we want to call processData even for empty chunks (IEND:bytesForData=0) at least once + if (bytesForData > 0 || crcn == 0) { + // in buffer mode we compute the CRC at the end + if (crcCheck && mode != ChunkReaderMode.BUFFER && bytesForData > 0) + chunkRaw.updateCrc(buf, off, bytesForData); - if (mode == ChunkReaderMode.BUFFER) { - // just copy the contents to the internal buffer - if (chunkRaw.data != buf && bytesForData > 0) { - // if the buffer passed if the same as this one, we don't copy the caller should know what he's doing - System.arraycopy(buf, off, chunkRaw.data, read, bytesForData); - } - } else if (mode == ChunkReaderMode.PROCESS) { - processData(read, buf, off, bytesForData); - } else { - // mode == ChunkReaderMode.SKIP; nothing to do - } - read += bytesForData; - off += bytesForData; - len -= bytesForData; - } - int crcRead = 0; - if (read == chunkRaw.len) { // data done - read crc? - crcRead = 4 - crcn; - if (crcRead > len) - crcRead = len; - if (crcRead > 0) { - if (buf != chunkRaw.crcval) - System.arraycopy(buf, off, chunkRaw.crcval, crcn, crcRead); - crcn += crcRead; - if (crcn == 4) { - if (crcCheck) { - if (mode == ChunkReaderMode.BUFFER) { // in buffer mode we compute the CRC on one single call - chunkRaw.updateCrc(chunkRaw.data, 0, chunkRaw.len); - } - chunkRaw.checkCrc(); - } - chunkDone(); - } - } - } - return bytesForData + crcRead; - } + if (mode == ChunkReaderMode.BUFFER) { + // just copy the contents to the internal buffer + if (chunkRaw.data != buf && bytesForData > 0) + // if the buffer passed if the same as this one, we don't copy the caller should know what he's doing + System.arraycopy(buf, off, chunkRaw.data, read, bytesForData); + } else if (mode == ChunkReaderMode.PROCESS) + processData(read, buf, off, bytesForData); + else { + // mode == ChunkReaderMode.SKIP; nothing to do + } + read += bytesForData; + off += bytesForData; + len -= bytesForData; + } + int crcRead = 0; + if (read == chunkRaw.len) { // data done - read crc? + crcRead = 4 - crcn; + if (crcRead > len) + crcRead = len; + if (crcRead > 0) { + if (buf != chunkRaw.crcval) + System.arraycopy(buf, off, chunkRaw.crcval, crcn, crcRead); + crcn += crcRead; + if (crcn == 4) { + if (crcCheck) { + if (mode == ChunkReaderMode.BUFFER) + chunkRaw.updateCrc(chunkRaw.data, 0, chunkRaw.len); + chunkRaw.checkCrc(); + } + chunkDone(); + } + } + } + return bytesForData + crcRead; + } - /** - * Chunks has been read - * - * @return true if we have read all chunk, including trailing CRC - */ - public final boolean isDone() { - return crcn == 4; // has read all 4 bytes from the crc - } + /** + * Chunks has been read + * + * @return true if we have read all chunk, including trailing CRC + */ + public final boolean isDone() { + return crcn == 4; // has read all 4 bytes from the crc + } - /** - * Determines if CRC should be checked. This should be called before starting reading. - * - * @param crcCheck - */ - public void setCrcCheck(boolean crcCheck) { - if (read != 0 && crcCheck && !this.crcCheck) - throw new PngjException("too late!"); - this.crcCheck = crcCheck; - } + /** + * Determines if CRC should be checked. This should be called before + * starting reading. + * + * @param crcCheck + */ + public void setCrcCheck(final boolean crcCheck) { + if (read != 0 && crcCheck && !this.crcCheck) + throw new PngjException("too late!"); + this.crcCheck = crcCheck; + } - /** - * This method will only be called in PROCESS mode, probably several times, each time with a new fragment of data - * inside the chunk. For chunks with zero-length data, this will still be called once. - * - * It's guaranteed that the data corresponds exclusively to this chunk data (no crc, no data from no other chunks, ) - * - * @param offsetInchunk data bytes that had already been read/processed for this chunk - * @param buf - * @param off - * @param len - */ - protected abstract void processData(int offsetInchunk, byte[] buf, int off, int len); + /** + * This method will only be called in PROCESS mode, probably several times, + * each time with a new fragment of data + * inside the chunk. For chunks with zero-length data, this will still be + * called once. + * + * It's guaranteed that the data corresponds exclusively to this chunk data + * (no crc, no data from no other chunks, ) + * + * @param offsetInchunk + * data bytes that had already been read/processed for this chunk + * @param buf + * @param off + * @param len + */ + protected abstract void processData(int offsetInchunk, byte[] buf, int off, int len); - /** - * This method will be called (in all modes) when the full chunk -including crc- has been read - */ - protected abstract void chunkDone(); + /** + * This method will be called (in all modes) when the full chunk -including + * crc- has been read + */ + protected abstract void chunkDone(); - public boolean isFromDeflatedSet() { - return false; - } + public boolean isFromDeflatedSet() { + return false; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((chunkRaw == null) ? 0 : chunkRaw.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (chunkRaw == null ? 0 : chunkRaw.hashCode()); + return result; + } - /** - * Equality (and hash) is basically delegated to the ChunkRaw - */ - @Override - public boolean equals(Object obj) { // delegates to chunkraw - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ChunkReader other = (ChunkReader) obj; - if (chunkRaw == null) { - if (other.chunkRaw != null) - return false; - } else if (!chunkRaw.equals(other.chunkRaw)) - return false; - return true; - } + /** + * Equality (and hash) is basically delegated to the ChunkRaw + */ + @Override + public boolean equals(final Object obj) { // delegates to chunkraw + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final ChunkReader other = (ChunkReader) obj; + if (chunkRaw == null) { + if (other.chunkRaw != null) + return false; + } else if (!chunkRaw.equals(other.chunkRaw)) + return false; + return true; + } - @Override - public String toString() { - return chunkRaw.toString(); - } + @Override + public String toString() { + return chunkRaw.toString(); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/ChunkSeqBuffering.java b/teavm/src/main/java/ar/com/hjg/pngj/ChunkSeqBuffering.java index 39e19dac..541eafdc 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/ChunkSeqBuffering.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/ChunkSeqBuffering.java @@ -2,29 +2,29 @@ package ar.com.hjg.pngj; /** * This loads the png as a plain sequence of chunks, buffering all - * - * Useful to do things like insert or delete a ancilllary chunk. This does not distinguish IDAT from others + * + * Useful to do things like insert or delete a ancilllary chunk. This does not + * distinguish IDAT from others **/ public class ChunkSeqBuffering extends ChunkSeqReader { - protected boolean checkCrc = true; + protected boolean checkCrc = true; - public ChunkSeqBuffering() { - super(); - } + public ChunkSeqBuffering() { + super(); + } - @Override - protected boolean isIdatKind(String id) { - return false; - } + @Override + protected boolean isIdatKind(final String id) { + return false; + } - @Override - protected boolean shouldCheckCrc(int len, String id) { - return checkCrc; - } - - public void setCheckCrc(boolean checkCrc) { - this.checkCrc = checkCrc; - } + @Override + protected boolean shouldCheckCrc(final int len, final String id) { + return checkCrc; + } + public void setCheckCrc(final boolean checkCrc) { + this.checkCrc = checkCrc; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/ChunkSeqReader.java b/teavm/src/main/java/ar/com/hjg/pngj/ChunkSeqReader.java index 82b661f1..5516615f 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/ChunkSeqReader.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/ChunkSeqReader.java @@ -12,385 +12,421 @@ import ar.com.hjg.pngj.chunks.ChunkHelper; /** * Consumes a stream of bytes that consist of a series of PNG-like chunks. *

- * This has little intelligence, it's quite low-level and general (it could even be used for a MNG stream, for example). + * This has little intelligence, it's quite low-level and general (it could even + * be used for a MNG stream, for example). * It supports signature recognition and idat deflate */ public class ChunkSeqReader implements IBytesConsumer { - protected static final int SIGNATURE_LEN = 8; - protected final boolean withSignature; + protected static final int SIGNATURE_LEN = 8; + protected final boolean withSignature; - private byte[] buf0 = new byte[8]; // for signature or chunk starts - private int buf0len = 0; + private final byte[] buf0 = new byte[8]; // for signature or chunk starts + private int buf0len = 0; - private boolean signatureDone = false; - private boolean done = false; // ended, normally or not + private boolean signatureDone = false; + private boolean done = false; // ended, normally or not - private int chunkCount = 0; + private int chunkCount = 0; - private long bytesCount = 0; + private long bytesCount = 0; - private DeflatedChunksSet curReaderDeflatedSet; // one instance is created for each - // "idat-like set". Normally one. + private DeflatedChunksSet curReaderDeflatedSet; // one instance is created for each + // "idat-like set". Normally one. - private ChunkReader curChunkReader; + private ChunkReader curChunkReader; - private long idatBytes; // this is only for the IDAT (not mrerely "idat-like") + private long idatBytes; // this is only for the IDAT (not mrerely "idat-like") - /** - * Creates a ChunkSeqReader (with signature) - */ - public ChunkSeqReader() { - this(true); - } + /** + * Creates a ChunkSeqReader (with signature) + */ + public ChunkSeqReader() { + this(true); + } - /** - * @param withSignature If true, the stream is assumed be prepended by 8 bit signature - */ - public ChunkSeqReader(boolean withSignature) { - this.withSignature = withSignature; - signatureDone = !withSignature; - } + /** + * @param withSignature + * If true, the stream is assumed be prepended by 8 bit signature + */ + public ChunkSeqReader(final boolean withSignature) { + this.withSignature = withSignature; + signatureDone = !withSignature; + } - /** - * Consumes (in general, partially) a number of bytes. A single call never involves more than one chunk. - * - * When the signature is read, it calls checkSignature() - * - * When the start of a chunk is detected, it calls {@link #startNewChunk(int, String, long)} - * - * When data from a chunk is being read, it delegates to {@link ChunkReader#feedBytes(byte[], int, int)} - * - * The caller might want to call this method more than once in succesion - * - * This should rarely be overriden - * - * @param buffer - * @param offset Offset in buffer - * @param len Valid bytes that can be consumed - * @return processed bytes, in the 1-len range. -1 if done. Only returns 0 if len=0. - **/ - public int consume(byte[] buffer, int offset, int len) { - if (done) - return -1; - if (len == 0) - return 0; // nothing to do - if (len < 0) - throw new PngjInputException("Bad len: " + len); - int processed = 0; - if (signatureDone) { - if (curChunkReader == null || curChunkReader.isDone()) { // new chunk: read first 8 bytes - int read0 = 8 - buf0len; - if (read0 > len) - read0 = len; - System.arraycopy(buffer, offset, buf0, buf0len, read0); - buf0len += read0; - processed += read0; - bytesCount += read0; - // len -= read0; - // offset += read0; - if (buf0len == 8) { // end reading chunk length and id - chunkCount++; - int clen = PngHelperInternal.readInt4fromBytes(buf0, 0); - String cid = ChunkHelper.toString(buf0, 4, 4); - startNewChunk(clen, cid, bytesCount - 8); - buf0len = 0; - } - } else { // reading chunk, delegates to curChunkReader - int read1 = curChunkReader.feedBytes(buffer, offset, len); - processed += read1; - bytesCount += read1; - } - } else { // reading signature - int read = SIGNATURE_LEN - buf0len; - if (read > len) - read = len; - System.arraycopy(buffer, offset, buf0, buf0len, read); - buf0len += read; - if (buf0len == SIGNATURE_LEN) { - checkSignature(buf0); - buf0len = 0; - signatureDone = true; - } - processed += read; - bytesCount += read; - } - return processed; - } + /** + * Consumes (in general, partially) a number of bytes. A single call never + * involves more than one chunk. + * + * When the signature is read, it calls checkSignature() + * + * When the start of a chunk is detected, it calls + * {@link #startNewChunk(int, String, long)} + * + * When data from a chunk is being read, it delegates to + * {@link ChunkReader#feedBytes(byte[], int, int)} + * + * The caller might want to call this method more than once in succesion + * + * This should rarely be overriden + * + * @param buffer + * @param offset + * Offset in buffer + * @param len + * Valid bytes that can be consumed + * @return processed bytes, in the 1-len range. -1 if done. Only returns 0 + * if len=0. + **/ + @Override + public int consume(final byte[] buffer, final int offset, final int len) { + if (done) + return -1; + if (len == 0) + return 0; // nothing to do + if (len < 0) + throw new PngjInputException("Bad len: " + len); + int processed = 0; + if (signatureDone) { + if (curChunkReader == null || curChunkReader.isDone()) { // new chunk: read first 8 bytes + int read0 = 8 - buf0len; + if (read0 > len) + read0 = len; + System.arraycopy(buffer, offset, buf0, buf0len, read0); + buf0len += read0; + processed += read0; + bytesCount += read0; + // len -= read0; + // offset += read0; + if (buf0len == 8) { // end reading chunk length and id + chunkCount++; + final int clen = PngHelperInternal.readInt4fromBytes(buf0, 0); + final String cid = ChunkHelper.toString(buf0, 4, 4); + startNewChunk(clen, cid, bytesCount - 8); + buf0len = 0; + } + } else { // reading chunk, delegates to curChunkReader + final int read1 = curChunkReader.feedBytes(buffer, offset, len); + processed += read1; + bytesCount += read1; + } + } else { // reading signature + int read = ChunkSeqReader.SIGNATURE_LEN - buf0len; + if (read > len) + read = len; + System.arraycopy(buffer, offset, buf0, buf0len, read); + buf0len += read; + if (buf0len == ChunkSeqReader.SIGNATURE_LEN) { + checkSignature(buf0); + buf0len = 0; + signatureDone = true; + } + processed += read; + bytesCount += read; + } + return processed; + } - /** - * Trys to feeds exactly len bytes, calling {@link #consume(byte[], int, int)} retrying if necessary. - * - * This should only be used in callback mode - * - * @return true if succceded - */ - public boolean feedAll(byte[] buf, int off, int len) { - while (len > 0) { - int n = consume(buf, off, len); - if (n < 1) - return false; - len -= n; - off += n; - } - return true; - } + /** + * Trys to feeds exactly len bytes, calling + * {@link #consume(byte[], int, int)} retrying if necessary. + * + * This should only be used in callback mode + * + * @return true if succceded + */ + public boolean feedAll(final byte[] buf, int off, int len) { + while (len > 0) { + final int n = consume(buf, off, len); + if (n < 1) + return false; + len -= n; + off += n; + } + return true; + } - /** - * Called for all chunks when a chunk start has been read (id and length), before the chunk data itself is read. It - * creates a new ChunkReader (field accesible via {@link #getCurChunkReader()}) in the corresponding mode, and - * eventually a curReaderDeflatedSet.(field accesible via {@link #getCurReaderDeflatedSet()}) - * - * To decide the mode and options, it calls {@link #shouldCheckCrc(int, String)}, - * {@link #shouldSkipContent(int, String)}, {@link #isIdatKind(String)}. Those methods should be overriden in - * preference to this; if overriden, this should be called first. - * - * The respective {@link ChunkReader#chunkDone()} method is directed to this {@link #postProcessChunk(ChunkReader)}. - * - * Instead of overriding this, see also {@link #createChunkReaderForNewChunk(String, int, long, boolean)} - */ - protected void startNewChunk(int len, String id, long offset) { - if (id.equals(ChunkHelper.IDAT)) - idatBytes += len; - boolean checkCrc = shouldCheckCrc(len, id); - boolean skip = shouldSkipContent(len, id); - boolean isIdatType = isIdatKind(id); - // PngHelperInternal.debug("start new chunk id=" + id + " off=" + offset + " skip=" + skip + " idat=" + - // isIdatType); - // first see if we should terminate an active curReaderDeflatedSet - boolean forCurrentIdatSet = false; - if (curReaderDeflatedSet != null) - forCurrentIdatSet = curReaderDeflatedSet.ackNextChunkId(id); - if (isIdatType && !skip) { // IDAT non skipped: create a DeflatedChunkReader owned by a idatSet - if (!forCurrentIdatSet) { - if (curReaderDeflatedSet != null && !curReaderDeflatedSet.isDone()) - throw new PngjInputException("new IDAT-like chunk when previous was not done"); - curReaderDeflatedSet = createIdatSet(id); - } - curChunkReader = new DeflatedChunkReader(len, id, checkCrc, offset, curReaderDeflatedSet) { - @Override - protected void chunkDone() { - super.chunkDone(); - postProcessChunk(this); - } - }; + /** + * Called for all chunks when a chunk start has been read (id and length), + * before the chunk data itself is read. It + * creates a new ChunkReader (field accesible via + * {@link #getCurChunkReader()}) in the corresponding mode, and + * eventually a curReaderDeflatedSet.(field accesible via + * {@link #getCurReaderDeflatedSet()}) + * + * To decide the mode and options, it calls + * {@link #shouldCheckCrc(int, String)}, + * {@link #shouldSkipContent(int, String)}, {@link #isIdatKind(String)}. + * Those methods should be overriden in + * preference to this; if overriden, this should be called first. + * + * The respective {@link ChunkReader#chunkDone()} method is directed to this + * {@link #postProcessChunk(ChunkReader)}. + * + * Instead of overriding this, see also + * {@link #createChunkReaderForNewChunk(String, int, long, boolean)} + */ + protected void startNewChunk(final int len, final String id, final long offset) { + if (id.equals(ChunkHelper.IDAT)) + idatBytes += len; + final boolean checkCrc = shouldCheckCrc(len, id); + final boolean skip = shouldSkipContent(len, id); + final boolean isIdatType = isIdatKind(id); + // PngHelperInternal.debug("start new chunk id=" + id + " off=" + offset + " skip=" + skip + " idat=" + + // isIdatType); + // first see if we should terminate an active curReaderDeflatedSet + boolean forCurrentIdatSet = false; + if (curReaderDeflatedSet != null) + forCurrentIdatSet = curReaderDeflatedSet.ackNextChunkId(id); + if (isIdatType && !skip) { // IDAT non skipped: create a DeflatedChunkReader owned by a idatSet + if (!forCurrentIdatSet) { + if (curReaderDeflatedSet != null && !curReaderDeflatedSet.isDone()) + throw new PngjInputException("new IDAT-like chunk when previous was not done"); + curReaderDeflatedSet = createIdatSet(id); + } + curChunkReader = new DeflatedChunkReader(len, id, checkCrc, offset, curReaderDeflatedSet) { + @Override + protected void chunkDone() { + super.chunkDone(); + postProcessChunk(this); + } + }; - } else { // for non-idat chunks (or skipped idat like) - curChunkReader = createChunkReaderForNewChunk(id, len, offset, skip); - if (!checkCrc) - curChunkReader.setCrcCheck(false); - } - } + } else { // for non-idat chunks (or skipped idat like) + curChunkReader = createChunkReaderForNewChunk(id, len, offset, skip); + if (!checkCrc) + curChunkReader.setCrcCheck(false); + } + } - /** - * This will be called for all chunks (even skipped), except for IDAT-like non-skiped chunks - * - * The default behaviour is to create a ChunkReader in BUFFER mode (or SKIP if skip==true) that calls - * {@link #postProcessChunk(ChunkReader)} (always) when done. - * - * @param id Chunk id - * @param len Chunk length - * @param offset offset inside PNG stream , merely informative - * @param skip flag: is true, the content will not be buffered (nor processed) - * @return a newly created ChunkReader that will create the ChunkRaw and then discarded - */ - protected ChunkReader createChunkReaderForNewChunk(String id, int len, long offset, boolean skip) { - return new ChunkReader(len, id, offset, skip ? ChunkReaderMode.SKIP : ChunkReaderMode.BUFFER) { - @Override - protected void chunkDone() { - postProcessChunk(this); - } + /** + * This will be called for all chunks (even skipped), except for IDAT-like + * non-skiped chunks + * + * The default behaviour is to create a ChunkReader in BUFFER mode (or SKIP + * if skip==true) that calls + * {@link #postProcessChunk(ChunkReader)} (always) when done. + * + * @param id + * Chunk id + * @param len + * Chunk length + * @param offset + * offset inside PNG stream , merely informative + * @param skip + * flag: is true, the content will not be buffered (nor + * processed) + * @return a newly created ChunkReader that will create the ChunkRaw and + * then discarded + */ + protected ChunkReader createChunkReaderForNewChunk(final String id, final int len, final long offset, + final boolean skip) { + return new ChunkReader(len, id, offset, skip ? ChunkReaderMode.SKIP : ChunkReaderMode.BUFFER) { + @Override + protected void chunkDone() { + postProcessChunk(this); + } - @Override - protected void processData(int offsetinChhunk, byte[] buf, int off, int len) { - throw new PngjExceptionInternal("should never happen"); - } - }; - } + @Override + protected void processData(final int offsetinChhunk, final byte[] buf, final int off, final int len) { + throw new PngjExceptionInternal("should never happen"); + } + }; + } - /** - * This is called after a chunk is read, in all modes - * - * This implementation only chenks the id of the first chunk, and process the IEND chunk (sets done=true) - ** - * Further processing should be overriden (call this first!) - **/ - protected void postProcessChunk(ChunkReader chunkR) { // called after chunk is read - if (chunkCount == 1) { - String cid = firstChunkId(); - if (cid != null && !cid.equals(chunkR.getChunkRaw().id)) - throw new PngjInputException("Bad first chunk: " + chunkR.getChunkRaw().id + " expected: " - + firstChunkId()); - } - if (chunkR.getChunkRaw().id.equals(endChunkId())) - done = true; - } + /** + * This is called after a chunk is read, in all modes + * + * This implementation only chenks the id of the first chunk, and process + * the IEND chunk (sets done=true) + ** + * Further processing should be overriden (call this first!) + **/ + protected void postProcessChunk(final ChunkReader chunkR) { // called after chunk is read + if (chunkCount == 1) { + final String cid = firstChunkId(); + if (cid != null && !cid.equals(chunkR.getChunkRaw().id)) + throw new PngjInputException("Bad first chunk: " + chunkR.getChunkRaw().id + " expected: " + firstChunkId()); + } + if (chunkR.getChunkRaw().id.equals(endChunkId())) + done = true; + } - /** - * DeflatedChunksSet factory. This implementation is quite dummy, it usually should be overriden. - */ - protected DeflatedChunksSet createIdatSet(String id) { - return new DeflatedChunksSet(id, 1024, 1024); // sizes: arbitrary This should normally be - // overriden - } + /** + * DeflatedChunksSet factory. This implementation is quite dummy, it usually + * should be overriden. + */ + protected DeflatedChunksSet createIdatSet(final String id) { + return new DeflatedChunksSet(id, 1024, 1024); // sizes: arbitrary This should normally be + // overriden + } - /** - * Decides if this Chunk is of "IDAT" kind (in concrete: if it is, and if it's not to be skiped, a DeflatedChunksSet - * will be created to deflate it and process+ the deflated data) - * - * This implementation always returns always false - * - * @param id - */ - protected boolean isIdatKind(String id) { - return false; - } + /** + * Decides if this Chunk is of "IDAT" kind (in concrete: if it is, and if + * it's not to be skiped, a DeflatedChunksSet + * will be created to deflate it and process+ the deflated data) + * + * This implementation always returns always false + * + * @param id + */ + protected boolean isIdatKind(final String id) { + return false; + } - /** - * Chunks can be skipped depending on id and/or length. Skipped chunks are still processed, but their data will be - * null, and CRC will never checked - * - * @param len - * @param id - */ - protected boolean shouldSkipContent(int len, String id) { - return false; - } + /** + * Chunks can be skipped depending on id and/or length. Skipped chunks are + * still processed, but their data will be + * null, and CRC will never checked + * + * @param len + * @param id + */ + protected boolean shouldSkipContent(final int len, final String id) { + return false; + } - protected boolean shouldCheckCrc(int len, String id) { - return true; - } + protected boolean shouldCheckCrc(final int len, final String id) { + return true; + } - /** - * Throws PngjInputException if bad signature - * - * @param buf Signature. Should be of length 8 - */ - protected void checkSignature(byte[] buf) { - if (!Arrays.equals(buf, PngHelperInternal.getPngIdSignature())) - throw new PngjInputException("Bad PNG signature"); - } + /** + * Throws PngjInputException if bad signature + * + * @param buf + * Signature. Should be of length 8 + */ + protected void checkSignature(final byte[] buf) { + if (!Arrays.equals(buf, PngHelperInternal.getPngIdSignature())) + throw new PngjInputException("Bad PNG signature"); + } - /** - * If false, we are still reading the signature - * - * @return true if signature has been read (or if we don't have signature) - */ - public boolean isSignatureDone() { - return signatureDone; - } + /** + * If false, we are still reading the signature + * + * @return true if signature has been read (or if we don't have signature) + */ + public boolean isSignatureDone() { + return signatureDone; + } - /** - * If true, we either have processe the IEND chunk, or close() has been called, or a fatal error has happened - */ - public boolean isDone() { - return done; - } + /** + * If true, we either have processe the IEND chunk, or close() has been + * called, or a fatal error has happened + */ + public boolean isDone() { + return done; + } - /** - * total of bytes read (buffered or not) - */ - public long getBytesCount() { - return bytesCount; - } + /** + * total of bytes read (buffered or not) + */ + public long getBytesCount() { + return bytesCount; + } - /** - * @return Chunks already read, including partial reading (currently reading) - */ - public int getChunkCount() { - return chunkCount; - } + /** + * @return Chunks already read, including partial reading (currently + * reading) + */ + public int getChunkCount() { + return chunkCount; + } - /** - * Currently reading chunk, or just ended reading - * - * @return null only if still reading signature - */ - public ChunkReader getCurChunkReader() { - return curChunkReader; - } + /** + * Currently reading chunk, or just ended reading + * + * @return null only if still reading signature + */ + public ChunkReader getCurChunkReader() { + return curChunkReader; + } - /** - * The latest deflated set (typically IDAT chunks) reader. Notice that there could be several idat sets (eg for APNG) - */ - public DeflatedChunksSet getCurReaderDeflatedSet() { - return curReaderDeflatedSet; - } + /** + * The latest deflated set (typically IDAT chunks) reader. Notice that there + * could be several idat sets (eg for APNG) + */ + public DeflatedChunksSet getCurReaderDeflatedSet() { + return curReaderDeflatedSet; + } - /** - * Closes this object and release resources. For normal termination or abort. Secure and idempotent. - */ - public void close() { // forced closing - if (curReaderDeflatedSet != null) - curReaderDeflatedSet.close(); - done = true; - } + /** + * Closes this object and release resources. For normal termination or + * abort. Secure and idempotent. + */ + public void close() { // forced closing + if (curReaderDeflatedSet != null) + curReaderDeflatedSet.close(); + done = true; + } - /** - * Returns true if we are not in middle of a chunk: we have just ended reading past chunk , or we are at the start, or - * end of signature, or we are done - */ - public boolean isAtChunkBoundary() { - return bytesCount == 0 || bytesCount == 8 || done || curChunkReader == null - || curChunkReader.isDone(); - } + /** + * Returns true if we are not in middle of a chunk: we have just ended + * reading past chunk , or we are at the start, or + * end of signature, or we are done + */ + public boolean isAtChunkBoundary() { + return bytesCount == 0 || bytesCount == 8 || done || curChunkReader == null || curChunkReader.isDone(); + } - /** - * Which should be the id of the first chunk - * - * @return null if you don't want to check it - */ - protected String firstChunkId() { - return "IHDR"; - } + /** + * Which should be the id of the first chunk + * + * @return null if you don't want to check it + */ + protected String firstChunkId() { + return "IHDR"; + } - /** - * Helper method, reports amount of bytes inside IDAT chunks. - * - * @return Bytes in IDAT chunks - */ - public long getIdatBytes() { - return idatBytes; - } + /** + * Helper method, reports amount of bytes inside IDAT chunks. + * + * @return Bytes in IDAT chunks + */ + public long getIdatBytes() { + return idatBytes; + } - /** - * Which should be the id of the last chunk - * - * @return "IEND" - */ - protected String endChunkId() { - return "IEND"; - } + /** + * Which should be the id of the last chunk + * + * @return "IEND" + */ + protected String endChunkId() { + return "IEND"; + } - /** - * Reads all content from a file. Helper method, only for callback mode - */ - public void feedFromFile(File f) { - try { - feedFromInputStream(new FileInputStream(f), true); - } catch (FileNotFoundException e) { - throw new PngjInputException(e.getMessage()); - } - } + /** + * Reads all content from a file. Helper method, only for callback mode + */ + public void feedFromFile(final File f) { + try { + feedFromInputStream(new FileInputStream(f), true); + } catch (final FileNotFoundException e) { + throw new PngjInputException(e.getMessage()); + } + } - /** - * Reads all content from an input stream. Helper method, only for callback mode - * - * @param is - * @param closeStream Closes the input stream when done (or if error) - */ - public void feedFromInputStream(InputStream is, boolean closeStream) { - BufferedStreamFeeder sf = new BufferedStreamFeeder(is); - sf.setCloseStream(closeStream); - try { - sf.feedAll(this); - } finally { - close(); - sf.close(); - } - } + /** + * Reads all content from an input stream. Helper method, only for callback + * mode + * + * @param is + * @param closeStream + * Closes the input stream when done (or if error) + */ + public void feedFromInputStream(final InputStream is, final boolean closeStream) { + final BufferedStreamFeeder sf = new BufferedStreamFeeder(is); + sf.setCloseStream(closeStream); + try { + sf.feedAll(this); + } finally { + close(); + sf.close(); + } + } - public void feedFromInputStream(InputStream is) { - feedFromInputStream(is, true); - } + public void feedFromInputStream(final InputStream is) { + feedFromInputStream(is, true); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/ChunkSeqReaderPng.java b/teavm/src/main/java/ar/com/hjg/pngj/ChunkSeqReaderPng.java index 44779c44..18b4777c 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/ChunkSeqReaderPng.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/ChunkSeqReaderPng.java @@ -16,298 +16,295 @@ import ar.com.hjg.pngj.chunks.PngChunkIHDR; import ar.com.hjg.pngj.chunks.PngChunkPLTE; /** - * Adds to ChunkSeqReader the storing of PngChunk, with a PngFactory, and imageInfo + deinterlacer. + * Adds to ChunkSeqReader the storing of PngChunk, with a PngFactory, and + * imageInfo + deinterlacer. *

- * Most usual PNG reading should use this class, or a {@link PngReader}, which is a thin wrapper over this. + * Most usual PNG reading should use this class, or a {@link PngReader}, which + * is a thin wrapper over this. */ public class ChunkSeqReaderPng extends ChunkSeqReader { - protected ImageInfo imageInfo; // initialized at parsing the IHDR - protected ImageInfo curImageInfo; // can vary, for apng - protected Deinterlacer deinterlacer; - protected int currentChunkGroup = -1; + protected ImageInfo imageInfo; // initialized at parsing the IHDR + protected ImageInfo curImageInfo; // can vary, for apng + protected Deinterlacer deinterlacer; + protected int currentChunkGroup = -1; - /** - * All chunks, but some of them can have the buffer empty (IDAT and skipped) - */ - protected ChunksList chunksList = null; - protected final boolean callbackMode; - private long bytesAncChunksLoaded = 0; // bytes loaded from buffered chunks non-critical chunks (data only) + /** + * All chunks, but some of them can have the buffer empty (IDAT and skipped) + */ + protected ChunksList chunksList = null; + protected final boolean callbackMode; + private long bytesAncChunksLoaded = 0; // bytes loaded from buffered chunks non-critical chunks (data only) - private boolean checkCrc = true; + private boolean checkCrc = true; - // --- parameters to be set prior to reading --- - private boolean includeNonBufferedChunks = false; + // --- parameters to be set prior to reading --- + private boolean includeNonBufferedChunks = false; - private Set chunksToSkip = new HashSet(); - private long maxTotalBytesRead = 0; - private long skipChunkMaxSize = 0; - private long maxBytesMetadata = 0; - private IChunkFactory chunkFactory; - private ChunkLoadBehaviour chunkLoadBehaviour = ChunkLoadBehaviour.LOAD_CHUNK_ALWAYS; + private final Set chunksToSkip = new HashSet<>(); + private long maxTotalBytesRead = 0; + private long skipChunkMaxSize = 0; + private long maxBytesMetadata = 0; + private IChunkFactory chunkFactory; + private ChunkLoadBehaviour chunkLoadBehaviour = ChunkLoadBehaviour.LOAD_CHUNK_ALWAYS; - public ChunkSeqReaderPng(boolean callbackMode) { - super(); - this.callbackMode = callbackMode; - chunkFactory = new ChunkFactory(); // default factory - } + public ChunkSeqReaderPng(final boolean callbackMode) { + super(); + this.callbackMode = callbackMode; + chunkFactory = new ChunkFactory(); // default factory + } - private void updateAndCheckChunkGroup(String id) { - if (id.equals(PngChunkIHDR.ID)) { // IDHR - if (currentChunkGroup < 0) - currentChunkGroup = ChunksList.CHUNK_GROUP_0_IDHR; - else - throw new PngjInputException("unexpected chunk " + id); - } else if (id.equals(PngChunkPLTE.ID)) { // PLTE - if ((currentChunkGroup == ChunksList.CHUNK_GROUP_0_IDHR || currentChunkGroup == ChunksList.CHUNK_GROUP_1_AFTERIDHR)) - currentChunkGroup = ChunksList.CHUNK_GROUP_2_PLTE; - else - throw new PngjInputException("unexpected chunk " + id); - } else if (id.equals(PngChunkIDAT.ID)) { // IDAT (no necessarily the first) - if ((currentChunkGroup >= ChunksList.CHUNK_GROUP_0_IDHR && currentChunkGroup <= ChunksList.CHUNK_GROUP_4_IDAT)) - currentChunkGroup = ChunksList.CHUNK_GROUP_4_IDAT; - else - throw new PngjInputException("unexpected chunk " + id); - } else if (id.equals(PngChunkIEND.ID)) { // END - if ((currentChunkGroup >= ChunksList.CHUNK_GROUP_4_IDAT)) - currentChunkGroup = ChunksList.CHUNK_GROUP_6_END; - else - throw new PngjInputException("unexpected chunk " + id); - } else { // ancillary - if (currentChunkGroup <= ChunksList.CHUNK_GROUP_1_AFTERIDHR) - currentChunkGroup = ChunksList.CHUNK_GROUP_1_AFTERIDHR; - else if (currentChunkGroup <= ChunksList.CHUNK_GROUP_3_AFTERPLTE) - currentChunkGroup = ChunksList.CHUNK_GROUP_3_AFTERPLTE; - else - currentChunkGroup = ChunksList.CHUNK_GROUP_5_AFTERIDAT; - } - } + private void updateAndCheckChunkGroup(final String id) { + if (id.equals(PngChunkIHDR.ID)) { // IDHR + if (currentChunkGroup < 0) + currentChunkGroup = ChunksList.CHUNK_GROUP_0_IDHR; + else + throw new PngjInputException("unexpected chunk " + id); + } else if (id.equals(PngChunkPLTE.ID)) { // PLTE + if (currentChunkGroup == ChunksList.CHUNK_GROUP_0_IDHR || currentChunkGroup == ChunksList.CHUNK_GROUP_1_AFTERIDHR) + currentChunkGroup = ChunksList.CHUNK_GROUP_2_PLTE; + else + throw new PngjInputException("unexpected chunk " + id); + } else if (id.equals(PngChunkIDAT.ID)) { // IDAT (no necessarily the first) + if (currentChunkGroup >= ChunksList.CHUNK_GROUP_0_IDHR && currentChunkGroup <= ChunksList.CHUNK_GROUP_4_IDAT) + currentChunkGroup = ChunksList.CHUNK_GROUP_4_IDAT; + else + throw new PngjInputException("unexpected chunk " + id); + } else if (id.equals(PngChunkIEND.ID)) { // END + if (currentChunkGroup >= ChunksList.CHUNK_GROUP_4_IDAT) + currentChunkGroup = ChunksList.CHUNK_GROUP_6_END; + else + throw new PngjInputException("unexpected chunk " + id); + } else if (currentChunkGroup <= ChunksList.CHUNK_GROUP_1_AFTERIDHR) + currentChunkGroup = ChunksList.CHUNK_GROUP_1_AFTERIDHR; + else if (currentChunkGroup <= ChunksList.CHUNK_GROUP_3_AFTERPLTE) + currentChunkGroup = ChunksList.CHUNK_GROUP_3_AFTERPLTE; + else + currentChunkGroup = ChunksList.CHUNK_GROUP_5_AFTERIDAT; + } - @Override - public boolean shouldSkipContent(int len, String id) { - if (super.shouldSkipContent(len, id)) - return true; - if (ChunkHelper.isCritical(id)) - return false;// critical chunks are never skipped - if (maxTotalBytesRead > 0 && len + getBytesCount() > maxTotalBytesRead) - throw new PngjInputException("Maximum total bytes to read exceeeded: " + maxTotalBytesRead - + " offset:" + getBytesCount() + " len=" + len); - if (chunksToSkip.contains(id)) - return true; // specific skip - if (skipChunkMaxSize > 0 && len > skipChunkMaxSize) - return true; // too big chunk - if (maxBytesMetadata > 0 && len > maxBytesMetadata - bytesAncChunksLoaded) - return true; // too much ancillary chunks loaded - switch (chunkLoadBehaviour) { - case LOAD_CHUNK_IF_SAFE: - if (!ChunkHelper.isSafeToCopy(id)) - return true; - break; - case LOAD_CHUNK_NEVER: - return true; - default: - break; - } - return false; - } + @Override + public boolean shouldSkipContent(final int len, final String id) { + if (super.shouldSkipContent(len, id)) + return true; + if (ChunkHelper.isCritical(id)) + return false;// critical chunks are never skipped + if (maxTotalBytesRead > 0 && len + getBytesCount() > maxTotalBytesRead) + throw new PngjInputException("Maximum total bytes to read exceeeded: " + maxTotalBytesRead + " offset:" + getBytesCount() + " len=" + len); + if (chunksToSkip.contains(id)) + return true; // specific skip + if (skipChunkMaxSize > 0 && len > skipChunkMaxSize) + return true; // too big chunk + if (maxBytesMetadata > 0 && len > maxBytesMetadata - bytesAncChunksLoaded) + return true; // too much ancillary chunks loaded + switch (chunkLoadBehaviour) { + case LOAD_CHUNK_IF_SAFE: + if (!ChunkHelper.isSafeToCopy(id)) + return true; + break; + case LOAD_CHUNK_NEVER: + return true; + default: + break; + } + return false; + } - public long getBytesChunksLoaded() { - return bytesAncChunksLoaded; - } + public long getBytesChunksLoaded() { + return bytesAncChunksLoaded; + } - public int getCurrentChunkGroup() { - return currentChunkGroup; - } + public int getCurrentChunkGroup() { + return currentChunkGroup; + } - public void setChunksToSkip(String... chunksToSkip) { - this.chunksToSkip.clear(); - for (String c : chunksToSkip) - this.chunksToSkip.add(c); - } + public void setChunksToSkip(final String... chunksToSkip) { + this.chunksToSkip.clear(); + for (final String c : chunksToSkip) + this.chunksToSkip.add(c); + } - public void addChunkToSkip(String chunkToSkip) { - this.chunksToSkip.add(chunkToSkip); - } + public void addChunkToSkip(final String chunkToSkip) { + chunksToSkip.add(chunkToSkip); + } - public void dontSkipChunk(String chunkToSkip) { - this.chunksToSkip.remove(chunkToSkip); - } + public void dontSkipChunk(final String chunkToSkip) { + chunksToSkip.remove(chunkToSkip); + } - public boolean firstChunksNotYetRead() { - return getCurrentChunkGroup() < ChunksList.CHUNK_GROUP_4_IDAT; - } + public boolean firstChunksNotYetRead() { + return getCurrentChunkGroup() < ChunksList.CHUNK_GROUP_4_IDAT; + } - @Override - protected void postProcessChunk(ChunkReader chunkR) { - super.postProcessChunk(chunkR); - if (chunkR.getChunkRaw().id.equals(PngChunkIHDR.ID)) { - PngChunkIHDR ch = new PngChunkIHDR(null); - ch.parseFromRaw(chunkR.getChunkRaw()); - imageInfo = ch.createImageInfo(); - curImageInfo = imageInfo; - if (ch.isInterlaced()) - deinterlacer = new Deinterlacer(curImageInfo); - chunksList = new ChunksList(imageInfo); - } - if (chunkR.mode == ChunkReaderMode.BUFFER && countChunkTypeAsAncillary(chunkR.getChunkRaw().id)) { - bytesAncChunksLoaded += chunkR.getChunkRaw().len; - } - if (chunkR.mode == ChunkReaderMode.BUFFER || includeNonBufferedChunks) { - PngChunk chunk = chunkFactory.createChunk(chunkR.getChunkRaw(), getImageInfo()); - chunksList.appendReadChunk(chunk, currentChunkGroup); - } - if (isDone()) { - processEndPng(); - } - } + @Override + protected void postProcessChunk(final ChunkReader chunkR) { + super.postProcessChunk(chunkR); + if (chunkR.getChunkRaw().id.equals(PngChunkIHDR.ID)) { + final PngChunkIHDR ch = new PngChunkIHDR(null); + ch.parseFromRaw(chunkR.getChunkRaw()); + imageInfo = ch.createImageInfo(); + curImageInfo = imageInfo; + if (ch.isInterlaced()) + deinterlacer = new Deinterlacer(curImageInfo); + chunksList = new ChunksList(imageInfo); + } + if (chunkR.mode == ChunkReaderMode.BUFFER && countChunkTypeAsAncillary(chunkR.getChunkRaw().id)) + bytesAncChunksLoaded += chunkR.getChunkRaw().len; + if (chunkR.mode == ChunkReaderMode.BUFFER || includeNonBufferedChunks) { + final PngChunk chunk = chunkFactory.createChunk(chunkR.getChunkRaw(), getImageInfo()); + chunksList.appendReadChunk(chunk, currentChunkGroup); + } + if (isDone()) + processEndPng(); + } - protected boolean countChunkTypeAsAncillary(String id) { - return !ChunkHelper.isCritical(id); - } + protected boolean countChunkTypeAsAncillary(final String id) { + return !ChunkHelper.isCritical(id); + } - @Override - protected DeflatedChunksSet createIdatSet(String id) { - IdatSet ids = new IdatSet(id, getCurImgInfo(), deinterlacer); - ids.setCallbackMode(callbackMode); - return ids; - } + @Override + protected DeflatedChunksSet createIdatSet(final String id) { + final IdatSet ids = new IdatSet(id, getCurImgInfo(), deinterlacer); + ids.setCallbackMode(callbackMode); + return ids; + } - public IdatSet getIdatSet() { - DeflatedChunksSet c = getCurReaderDeflatedSet(); - return c instanceof IdatSet ? (IdatSet) c : null; - } + public IdatSet getIdatSet() { + final DeflatedChunksSet c = getCurReaderDeflatedSet(); + return c instanceof IdatSet ? (IdatSet) c : null; + } - @Override - protected boolean isIdatKind(String id) { - return id.equals(PngChunkIDAT.ID); - } + @Override + protected boolean isIdatKind(final String id) { + return id.equals(PngChunkIDAT.ID); + } - @Override - public int consume(byte[] buf, int off, int len) { - return super.consume(buf, off, len); - } + @Override + public int consume(final byte[] buf, final int off, final int len) { + return super.consume(buf, off, len); + } - /** - * sets a custom chunk factory. This is typically called with a custom class extends ChunkFactory, to adds custom - * chunks to the default well-know ones - * - * @param chunkFactory - */ - public void setChunkFactory(IChunkFactory chunkFactory) { - this.chunkFactory = chunkFactory; - } + /** + * sets a custom chunk factory. This is typically called with a custom class + * extends ChunkFactory, to adds custom + * chunks to the default well-know ones + * + * @param chunkFactory + */ + public void setChunkFactory(final IChunkFactory chunkFactory) { + this.chunkFactory = chunkFactory; + } - /** - * Things to be done after IEND processing. This is not called if prematurely closed. - */ - protected void processEndPng() { - // nothing to do - } + /** + * Things to be done after IEND processing. This is not called if + * prematurely closed. + */ + protected void processEndPng() { + // nothing to do + } - public ImageInfo getImageInfo() { - return imageInfo; - } + public ImageInfo getImageInfo() { + return imageInfo; + } - public boolean isInterlaced() { - return deinterlacer != null; - } + public boolean isInterlaced() { + return deinterlacer != null; + } - public Deinterlacer getDeinterlacer() { - return deinterlacer; - } + public Deinterlacer getDeinterlacer() { + return deinterlacer; + } - @Override - protected void startNewChunk(int len, String id, long offset) { - updateAndCheckChunkGroup(id); - super.startNewChunk(len, id, offset); - } + @Override + protected void startNewChunk(final int len, final String id, final long offset) { + updateAndCheckChunkGroup(id); + super.startNewChunk(len, id, offset); + } - @Override - public void close() { - if (currentChunkGroup != ChunksList.CHUNK_GROUP_6_END)// this could only happen if forced close - currentChunkGroup = ChunksList.CHUNK_GROUP_6_END; - super.close(); - } + @Override + public void close() { + if (currentChunkGroup != ChunksList.CHUNK_GROUP_6_END)// this could only happen if forced close + currentChunkGroup = ChunksList.CHUNK_GROUP_6_END; + super.close(); + } - public List getChunks() { - return chunksList.getChunks(); - } + public List getChunks() { + return chunksList.getChunks(); + } - public void setMaxTotalBytesRead(long maxTotalBytesRead) { - this.maxTotalBytesRead = maxTotalBytesRead; - } + public void setMaxTotalBytesRead(final long maxTotalBytesRead) { + this.maxTotalBytesRead = maxTotalBytesRead; + } - public long getSkipChunkMaxSize() { - return skipChunkMaxSize; - } + public long getSkipChunkMaxSize() { + return skipChunkMaxSize; + } - public void setSkipChunkMaxSize(long skipChunkMaxSize) { - this.skipChunkMaxSize = skipChunkMaxSize; - } + public void setSkipChunkMaxSize(final long skipChunkMaxSize) { + this.skipChunkMaxSize = skipChunkMaxSize; + } - public long getMaxBytesMetadata() { - return maxBytesMetadata; - } + public long getMaxBytesMetadata() { + return maxBytesMetadata; + } - public void setMaxBytesMetadata(long maxBytesMetadata) { - this.maxBytesMetadata = maxBytesMetadata; - } + public void setMaxBytesMetadata(final long maxBytesMetadata) { + this.maxBytesMetadata = maxBytesMetadata; + } - public long getMaxTotalBytesRead() { - return maxTotalBytesRead; - } + public long getMaxTotalBytesRead() { + return maxTotalBytesRead; + } - @Override - protected boolean shouldCheckCrc(int len, String id) { - return checkCrc; - } + @Override + protected boolean shouldCheckCrc(final int len, final String id) { + return checkCrc; + } - public boolean isCheckCrc() { - return checkCrc; - } + public boolean isCheckCrc() { + return checkCrc; + } - public void setCheckCrc(boolean checkCrc) { - this.checkCrc = checkCrc; - } + public void setCheckCrc(final boolean checkCrc) { + this.checkCrc = checkCrc; + } - public boolean isCallbackMode() { - return callbackMode; - } + public boolean isCallbackMode() { + return callbackMode; + } - public Set getChunksToSkip() { - return chunksToSkip; - } + public Set getChunksToSkip() { + return chunksToSkip; + } - public void setChunkLoadBehaviour(ChunkLoadBehaviour chunkLoadBehaviour) { - this.chunkLoadBehaviour = chunkLoadBehaviour; - } + public void setChunkLoadBehaviour(final ChunkLoadBehaviour chunkLoadBehaviour) { + this.chunkLoadBehaviour = chunkLoadBehaviour; + } - public ImageInfo getCurImgInfo() { - return curImageInfo; - } - - public void updateCurImgInfo(ImageInfo iminfo) { - if (!iminfo.equals(curImageInfo)) { - curImageInfo = iminfo; - } - if (deinterlacer != null) - deinterlacer = new Deinterlacer(curImageInfo); // we could reset it, but... - } - - /** - * If true, the chunks with no data (because skipped or because processed like IDAT-type) are still stored in the - * PngChunks list, which might be more informative. - * - * Setting this to false saves a few bytes - * - * Default: false - * - * @param includeNonBufferedChunks - */ - public void setIncludeNonBufferedChunks(boolean includeNonBufferedChunks) { - this.includeNonBufferedChunks = includeNonBufferedChunks; - } + public ImageInfo getCurImgInfo() { + return curImageInfo; + } + public void updateCurImgInfo(final ImageInfo iminfo) { + if (!iminfo.equals(curImageInfo)) + curImageInfo = iminfo; + if (deinterlacer != null) + deinterlacer = new Deinterlacer(curImageInfo); // we could reset it, but... + } + /** + * If true, the chunks with no data (because skipped or because processed + * like IDAT-type) are still stored in the + * PngChunks list, which might be more informative. + * + * Setting this to false saves a few bytes + * + * Default: false + * + * @param includeNonBufferedChunks + */ + public void setIncludeNonBufferedChunks(final boolean includeNonBufferedChunks) { + this.includeNonBufferedChunks = includeNonBufferedChunks; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/ChunkSeqSkipping.java b/teavm/src/main/java/ar/com/hjg/pngj/ChunkSeqSkipping.java index 5448c118..96d765ac 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/ChunkSeqSkipping.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/ChunkSeqSkipping.java @@ -7,64 +7,70 @@ import ar.com.hjg.pngj.ChunkReader.ChunkReaderMode; import ar.com.hjg.pngj.chunks.ChunkRaw; /** - * This simple reader skips all chunks contents and stores the chunkRaw in a list. Useful to read chunks structure. - * - * Optionally the contents might be processed. This doesn't distinguish IDAT chunks + * This simple reader skips all chunks contents and stores the chunkRaw in a + * list. Useful to read chunks structure. + * + * Optionally the contents might be processed. This doesn't distinguish IDAT + * chunks */ public class ChunkSeqSkipping extends ChunkSeqReader { - private List chunks = new ArrayList(); - private boolean skip = true; + private final List chunks = new ArrayList<>(); + private boolean skip = true; - /** - * @param skipAll if true, contents will be truly skipped, and CRC will not be computed - */ - public ChunkSeqSkipping(boolean skipAll) { - super(true); - skip = skipAll; - } + /** + * @param skipAll + * if true, contents will be truly skipped, and CRC will not be + * computed + */ + public ChunkSeqSkipping(final boolean skipAll) { + super(true); + skip = skipAll; + } - public ChunkSeqSkipping() { - this(true); - } + public ChunkSeqSkipping() { + this(true); + } - protected ChunkReader createChunkReaderForNewChunk(String id, int len, long offset, boolean skip) { - return new ChunkReader(len, id, offset, skip ? ChunkReaderMode.SKIP : ChunkReaderMode.PROCESS) { - @Override - protected void chunkDone() { - postProcessChunk(this); - } + @Override + protected ChunkReader createChunkReaderForNewChunk(final String id, final int len, final long offset, + final boolean skip) { + return new ChunkReader(len, id, offset, skip ? ChunkReaderMode.SKIP : ChunkReaderMode.PROCESS) { + @Override + protected void chunkDone() { + postProcessChunk(this); + } - @Override - protected void processData(int offsetinChhunk, byte[] buf, int off, int len) { - processChunkContent(getChunkRaw(), offsetinChhunk, buf, off, len); - } - }; - } + @Override + protected void processData(final int offsetinChhunk, final byte[] buf, final int off, final int len) { + processChunkContent(getChunkRaw(), offsetinChhunk, buf, off, len); + } + }; + } - protected void processChunkContent(ChunkRaw chunkRaw, int offsetinChhunk, byte[] buf, int off, - int len) { - // does nothing - } + protected void processChunkContent(final ChunkRaw chunkRaw, final int offsetinChhunk, final byte[] buf, + final int off, final int len) { + // does nothing + } - @Override - protected void postProcessChunk(ChunkReader chunkR) { - super.postProcessChunk(chunkR); - chunks.add(chunkR.getChunkRaw()); - } + @Override + protected void postProcessChunk(final ChunkReader chunkR) { + super.postProcessChunk(chunkR); + chunks.add(chunkR.getChunkRaw()); + } - @Override - protected boolean shouldSkipContent(int len, String id) { - return skip; - } + @Override + protected boolean shouldSkipContent(final int len, final String id) { + return skip; + } - @Override - protected boolean isIdatKind(String id) { - return false; - } + @Override + protected boolean isIdatKind(final String id) { + return false; + } - public List getChunks() { - return chunks; - } + public List getChunks() { + return chunks; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/DeflatedChunkReader.java b/teavm/src/main/java/ar/com/hjg/pngj/DeflatedChunkReader.java index 6abac098..426f53e8 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/DeflatedChunkReader.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/DeflatedChunkReader.java @@ -3,81 +3,76 @@ package ar.com.hjg.pngj; import ar.com.hjg.pngj.chunks.PngChunkFDAT; /** - * - * Specialization of ChunkReader, for IDAT-like chunks. These chunks are part of a set of similar chunks (contiguos + * + * Specialization of ChunkReader, for IDAT-like chunks. These chunks are part of + * a set of similar chunks (contiguos * normally, not necessariyl) which conforms a zlib stream */ public class DeflatedChunkReader extends ChunkReader { - protected final DeflatedChunksSet deflatedChunksSet; - protected boolean alsoBuffer = false; + protected final DeflatedChunksSet deflatedChunksSet; + protected boolean alsoBuffer = false; - protected boolean skipBytes = false; // fDAT (APNG) skips 4 bytes) - protected byte[] skippedBytes; // only for fDAT - protected int seqNumExpected = -1; // only for fDAT + protected boolean skipBytes = false; // fDAT (APNG) skips 4 bytes) + protected byte[] skippedBytes; // only for fDAT + protected int seqNumExpected = -1; // only for fDAT - public DeflatedChunkReader(int clen, String chunkid, boolean checkCrc, long offsetInPng, - DeflatedChunksSet iDatSet) { - super(clen, chunkid, offsetInPng, ChunkReaderMode.PROCESS); - this.deflatedChunksSet = iDatSet; - if (chunkid.equals(PngChunkFDAT.ID)) { - skipBytes = true; - skippedBytes = new byte[4]; - } - iDatSet.appendNewChunk(this); - } + public DeflatedChunkReader(final int clen, final String chunkid, final boolean checkCrc, final long offsetInPng, final DeflatedChunksSet iDatSet) { + super(clen, chunkid, offsetInPng, ChunkReaderMode.PROCESS); + deflatedChunksSet = iDatSet; + if (chunkid.equals(PngChunkFDAT.ID)) { + skipBytes = true; + skippedBytes = new byte[4]; + } + iDatSet.appendNewChunk(this); + } - /** - * Delegates to ChunkReaderDeflatedSet.processData() - */ - @Override - protected void processData(int offsetInchunk, byte[] buf, int off, int len) { - if (skipBytes && offsetInchunk < 4) {// only for APNG (sigh) - for (int oc = offsetInchunk; oc < 4 && len > 0; oc++, off++, len--) - skippedBytes[oc] = buf[off]; - } - if (len > 0) { // delegate to idatSet - deflatedChunksSet.processBytes(buf, off, len); - if (alsoBuffer) { // very rare! - System.arraycopy(buf, off, getChunkRaw().data, read, len); - } - } - } + /** + * Delegates to ChunkReaderDeflatedSet.processData() + */ + @Override + protected void processData(final int offsetInchunk, final byte[] buf, int off, int len) { + if (skipBytes && offsetInchunk < 4) + for (int oc = offsetInchunk; oc < 4 && len > 0; oc++, off++, len--) + skippedBytes[oc] = buf[off]; + if (len > 0) { // delegate to idatSet + deflatedChunksSet.processBytes(buf, off, len); + if (alsoBuffer) + System.arraycopy(buf, off, getChunkRaw().data, read, len); + } + } - /** - * only a stupid check for fDAT (I wonder how many APGN readers do this) - */ - @Override - protected void chunkDone() { - if (skipBytes && getChunkRaw().id.equals(PngChunkFDAT.ID)) { - if (seqNumExpected >= 0) { - int seqNum = PngHelperInternal.readInt4fromBytes(skippedBytes, 0); - if (seqNum != seqNumExpected) - throw new PngjInputException("bad chunk sequence for fDAT chunk " + seqNum + " expected " - + seqNumExpected); - } - } - } + /** + * only a stupid check for fDAT (I wonder how many APGN readers do this) + */ + @Override + protected void chunkDone() { + if (skipBytes && getChunkRaw().id.equals(PngChunkFDAT.ID)) + if (seqNumExpected >= 0) { + final int seqNum = PngHelperInternal.readInt4fromBytes(skippedBytes, 0); + if (seqNum != seqNumExpected) + throw new PngjInputException("bad chunk sequence for fDAT chunk " + seqNum + " expected " + seqNumExpected); + } + } - @Override - public boolean isFromDeflatedSet() { - return true; - } + @Override + public boolean isFromDeflatedSet() { + return true; + } - /** - * In some rare cases you might want to also buffer the data? - */ - public void setAlsoBuffer() { - if (read > 0) - throw new RuntimeException("too late"); - alsoBuffer = true; - getChunkRaw().allocData(); - } - - /** only relevant for fDAT */ - public void setSeqNumExpected(int seqNumExpected) { - this.seqNumExpected = seqNumExpected; - } + /** + * In some rare cases you might want to also buffer the data? + */ + public void setAlsoBuffer() { + if (read > 0) + throw new RuntimeException("too late"); + alsoBuffer = true; + getChunkRaw().allocData(); + } + /** only relevant for fDAT */ + public void setSeqNumExpected(final int seqNumExpected) { + this.seqNumExpected = seqNumExpected; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/DeflatedChunksSet.java b/teavm/src/main/java/ar/com/hjg/pngj/DeflatedChunksSet.java index 1d496e8c..b4feeb32 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/DeflatedChunksSet.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/DeflatedChunksSet.java @@ -6,13 +6,15 @@ import java.util.zip.Inflater; /** * A set of IDAT-like chunks which, concatenated, form a zlib stream. *

- * The inflated stream is intented to be read as a sequence of "rows", of which the caller knows the lengths (not + * The inflated stream is intented to be read as a sequence of "rows", of which + * the caller knows the lengths (not * necessary equal) and number. *

* Eg: For IDAT non-interlaced images, a row has bytesPerRow + 1 filter byte
* For interlaced images, the lengths are variable. *

- * This class can work in sync (polled) mode or async (callback) mode. But for callback mode the method + * This class can work in sync (polled) mode or async (callback) mode. But for + * callback mode the method * processRowCallback() must be overriden *

* See {@link IdatSet}, which is mostly used and has a slightly simpler use.
@@ -20,398 +22,401 @@ import java.util.zip.Inflater; */ public class DeflatedChunksSet { - protected byte[] row; // a "row" here means a raw (uncopressed filtered) part of the IDAT stream, - // normally a image row (or subimage row for interlaced) plus a filter byte - private int rowfilled; // effective/valid length of row - private int rowlen; // what amount of bytes is to be interpreted as a complete "row". can change - // (for interlaced) - private int rown; // only coincide with image row if non-interlaced - incremented by - // setNextRowSize() + protected byte[] row; // a "row" here means a raw (uncopressed filtered) part of the IDAT stream, + // normally a image row (or subimage row for interlaced) plus a filter byte + private int rowfilled; // effective/valid length of row + private int rowlen; // what amount of bytes is to be interpreted as a complete "row". can change + // (for interlaced) + private int rown; // only coincide with image row if non-interlaced - incremented by + // setNextRowSize() - /* - * States WAITING_FOR_INPUT ROW_READY WORK_DONE TERMINATED - * - * processBytes() is externally called, prohibited in READY (in DONE it's ignored) - * - * WARNING: inflater.finished() != DONE (not enough, not neccesary) DONE means that we have already uncompressed all - * the data of interest. - * - * In non-callback mode, prepareForNextRow() is also externally called, in - * - * Flow: - processBytes() calls inflateData() - inflateData() : if buffer is filled goes to READY else if ! - * inf.finished goes to WAITING else if any data goes to READY (incomplete data to be read) else goes to DONE - in - * Callback mode, after going to READY, n=processCallback() is called and then prepareForNextRow(n) is called. - in - * Polled mode, prepareForNextRow(n) must be called from outside (after checking state=READY) - prepareForNextRow(n) - * goes to DONE if n==0 calls inflateData() again - end() goes to DONE - */ - private enum State { - WAITING_FOR_INPUT, // waiting for more input - ROW_READY, // ready for consumption (might be less than fully filled), ephemeral for CALLBACK - // mode - WORK_DONE, // all data of interest has been read, but we might accept still more trailing chunks - // (we'll ignore them) - TERMINATED; // we are done, and also won't accept more IDAT chunks + /* + * States WAITING_FOR_INPUT ROW_READY WORK_DONE TERMINATED + * + * processBytes() is externally called, prohibited in READY (in DONE it's ignored) + * + * WARNING: inflater.finished() != DONE (not enough, not neccesary) DONE means that we have already uncompressed all + * the data of interest. + * + * In non-callback mode, prepareForNextRow() is also externally called, in + * + * Flow: - processBytes() calls inflateData() - inflateData() : if buffer is filled goes to READY else if ! + * inf.finished goes to WAITING else if any data goes to READY (incomplete data to be read) else goes to DONE - in + * Callback mode, after going to READY, n=processCallback() is called and then prepareForNextRow(n) is called. - in + * Polled mode, prepareForNextRow(n) must be called from outside (after checking state=READY) - prepareForNextRow(n) + * goes to DONE if n==0 calls inflateData() again - end() goes to DONE + */ + private enum State { + WAITING_FOR_INPUT, // waiting for more input + ROW_READY, // ready for consumption (might be less than fully filled), ephemeral for CALLBACK + // mode + WORK_DONE, // all data of interest has been read, but we might accept still more trailing chunks + // (we'll ignore them) + TERMINATED; // we are done, and also won't accept more IDAT chunks - public boolean isDone() { - return this == WORK_DONE || this == TERMINATED; - } // the caller has already uncompressed all the data of interest or EOF + public boolean isDone() { + return this == WORK_DONE || this == TERMINATED; + } // the caller has already uncompressed all the data of interest or EOF - public boolean isTerminated() { - return this == TERMINATED; - } // we dont accept more chunks - } + public boolean isTerminated() { + return this == TERMINATED; + } // we dont accept more chunks + } - State state = State.WAITING_FOR_INPUT; // never null + State state = State.WAITING_FOR_INPUT; // never null - private Inflater inf; - private final boolean infOwn; // true if we own the inflater (we created it) + private Inflater inf; + private final boolean infOwn; // true if we own the inflater (we created it) - private DeflatedChunkReader curChunk; + private DeflatedChunkReader curChunk; - private boolean callbackMode = true; - private long nBytesIn = 0; // count the total compressed bytes that have been fed - private long nBytesOut = 0; // count the total uncompressed bytes - int chunkNum = -1; // incremented at each new chunk start - int firstChunqSeqNum = -1; // expected seq num for first chunk. used only for fDAT (APNG) + private boolean callbackMode = true; + private long nBytesIn = 0; // count the total compressed bytes that have been fed + private long nBytesOut = 0; // count the total uncompressed bytes + int chunkNum = -1; // incremented at each new chunk start + int firstChunqSeqNum = -1; // expected seq num for first chunk. used only for fDAT (APNG) - /** - * All IDAT-like chunks that form a same DeflatedChunksSet should have the same id - */ - public final String chunkid; + /** + * All IDAT-like chunks that form a same DeflatedChunksSet should have the + * same id + */ + public final String chunkid; - /** - * @param initialRowLen Length in bytes of first "row" (see description) - * @param maxRowLen Max length in bytes of "rows" - * @param inflater Can be null. If not null, must be already reset (and it must be closed/released by caller!) - */ - public DeflatedChunksSet(String chunkid, int initialRowLen, int maxRowLen, Inflater inflater, - byte[] buffer) { - this.chunkid = chunkid; - this.rowlen = initialRowLen; - if (initialRowLen < 1 || maxRowLen < initialRowLen) - throw new PngjException("bad inital row len " + initialRowLen); - if (inflater != null) { - this.inf = inflater; - infOwn = false; - } else { - this.inf = new Inflater(); - infOwn = true; // inflater is own, we will release on close() - } - this.row = buffer != null && buffer.length >= initialRowLen ? buffer : new byte[maxRowLen]; - rown = -1; - this.state = State.WAITING_FOR_INPUT; - try { - prepareForNextRow(initialRowLen); - } catch (RuntimeException e) { - close(); - throw e; - } - } + /** + * @param initialRowLen + * Length in bytes of first "row" (see description) + * @param maxRowLen + * Max length in bytes of "rows" + * @param inflater + * Can be null. If not null, must be already reset (and it must + * be closed/released by caller!) + */ + public DeflatedChunksSet(final String chunkid, final int initialRowLen, final int maxRowLen, final Inflater inflater, final byte[] buffer) { + this.chunkid = chunkid; + rowlen = initialRowLen; + if (initialRowLen < 1 || maxRowLen < initialRowLen) + throw new PngjException("bad inital row len " + initialRowLen); + if (inflater != null) { + inf = inflater; + infOwn = false; + } else { + inf = new Inflater(); + infOwn = true; // inflater is own, we will release on close() + } + row = buffer != null && buffer.length >= initialRowLen ? buffer : new byte[maxRowLen]; + rown = -1; + state = State.WAITING_FOR_INPUT; + try { + prepareForNextRow(initialRowLen); + } catch (final RuntimeException e) { + close(); + throw e; + } + } - public DeflatedChunksSet(String chunkid, int initialRowLen, int maxRowLen) { - this(chunkid, initialRowLen, maxRowLen, null, null); - } + public DeflatedChunksSet(final String chunkid, final int initialRowLen, final int maxRowLen) { + this(chunkid, initialRowLen, maxRowLen, null, null); + } - protected void appendNewChunk(DeflatedChunkReader cr) { - // all chunks must have same id - if (!this.chunkid.equals(cr.getChunkRaw().id)) - throw new PngjInputException("Bad chunk inside IdatSet, id:" + cr.getChunkRaw().id - + ", expected:" + this.chunkid); - this.curChunk = cr; - chunkNum++; - if (firstChunqSeqNum >= 0) - cr.setSeqNumExpected(chunkNum + firstChunqSeqNum); - } + protected void appendNewChunk(final DeflatedChunkReader cr) { + // all chunks must have same id + if (!chunkid.equals(cr.getChunkRaw().id)) + throw new PngjInputException("Bad chunk inside IdatSet, id:" + cr.getChunkRaw().id + ", expected:" + chunkid); + curChunk = cr; + chunkNum++; + if (firstChunqSeqNum >= 0) + cr.setSeqNumExpected(chunkNum + firstChunqSeqNum); + } - /** - * Feeds the inflater with the compressed bytes - * - * In poll mode, the caller should not call repeatedly this, without consuming first, checking - * isDataReadyForConsumer() - * - * @param buf - * @param off - * @param len - */ - protected void processBytes(byte[] buf, int off, int len) { - nBytesIn += len; - // PngHelperInternal.LOGGER.info("processing compressed bytes in chunkreader : " + len); - if (len < 1 || state.isDone()) - return; - if (state == State.ROW_READY) - throw new PngjInputException("this should only be called if waitingForMoreInput"); - if (inf.needsDictionary() || !inf.needsInput()) - throw new RuntimeException("should not happen"); - inf.setInput(buf, off, len); - // PngHelperInternal.debug("entering processs bytes, state=" + state + - // " callback="+callbackMode); - if (isCallbackMode()) { - while (inflateData()) { - int nextRowLen = processRowCallback(); - prepareForNextRow(nextRowLen); - if (isDone()) - processDoneCallback(); - } - } else - inflateData(); - } + /** + * Feeds the inflater with the compressed bytes + * + * In poll mode, the caller should not call repeatedly this, without + * consuming first, checking + * isDataReadyForConsumer() + * + * @param buf + * @param off + * @param len + */ + protected void processBytes(final byte[] buf, final int off, final int len) { + nBytesIn += len; + // PngHelperInternal.LOGGER.info("processing compressed bytes in chunkreader : " + len); + if (len < 1 || state.isDone()) + return; + if (state == State.ROW_READY) + throw new PngjInputException("this should only be called if waitingForMoreInput"); + if (inf.needsDictionary() || !inf.needsInput()) + throw new RuntimeException("should not happen"); + inf.setInput(buf, off, len); + // PngHelperInternal.debug("entering processs bytes, state=" + state + + // " callback="+callbackMode); + if (isCallbackMode()) + while (inflateData()) { + final int nextRowLen = processRowCallback(); + prepareForNextRow(nextRowLen); + if (isDone()) + processDoneCallback(); + } + else + inflateData(); + } - /* - * This never inflates more than one row This returns true if this has resulted in a row being ready and preprocessed - * with preProcessRow (in callback mode, we should call immediately processRowCallback() and - * prepareForNextRow(nextRowLen) - */ - private boolean inflateData() { - try { - // PngHelperInternal.debug("entering inflateData bytes, state=" + state + - // " callback="+callbackMode); - if (state == State.ROW_READY) - throw new PngjException("invalid state");// assert - if (state.isDone()) - return false; - int ninflated = 0; - if (row == null || row.length < rowlen) - row = new byte[rowlen]; // should not happen - if (rowfilled < rowlen && !inf.finished()) { - try { - ninflated = inf.inflate(row, rowfilled, rowlen - rowfilled); - } catch (DataFormatException e) { - throw new PngjInputException("error decompressing zlib stream ", e); - } - rowfilled += ninflated; - nBytesOut += ninflated; - } - State nextstate = null; - if (rowfilled == rowlen) - nextstate = State.ROW_READY; // complete row, process it - else if (!inf.finished()) - nextstate = State.WAITING_FOR_INPUT; - else if (rowfilled > 0) - nextstate = State.ROW_READY; // complete row, process it - else { - nextstate = State.WORK_DONE; // eof, no more data - } - state = nextstate; - if (state == State.ROW_READY) { - preProcessRow(); - return true; - } - } catch (RuntimeException e) { - close(); - throw e; - } - return false; - } + /* + * This never inflates more than one row This returns true if this has resulted in a row being ready and preprocessed + * with preProcessRow (in callback mode, we should call immediately processRowCallback() and + * prepareForNextRow(nextRowLen) + */ + private boolean inflateData() { + try { + // PngHelperInternal.debug("entering inflateData bytes, state=" + state + + // " callback="+callbackMode); + if (state == State.ROW_READY) + throw new PngjException("invalid state");// assert + if (state.isDone()) + return false; + int ninflated = 0; + if (row == null || row.length < rowlen) + row = new byte[rowlen]; // should not happen + if (rowfilled < rowlen && !inf.finished()) { + try { + ninflated = inf.inflate(row, rowfilled, rowlen - rowfilled); + } catch (final DataFormatException e) { + throw new PngjInputException("error decompressing zlib stream ", e); + } + rowfilled += ninflated; + nBytesOut += ninflated; + } + State nextstate = null; + if (rowfilled == rowlen) + nextstate = State.ROW_READY; // complete row, process it + else if (!inf.finished()) + nextstate = State.WAITING_FOR_INPUT; + else if (rowfilled > 0) + nextstate = State.ROW_READY; // complete row, process it + else + nextstate = State.WORK_DONE; // eof, no more data + state = nextstate; + if (state == State.ROW_READY) { + preProcessRow(); + return true; + } + } catch (final RuntimeException e) { + close(); + throw e; + } + return false; + } - /** - * Called automatically in all modes when a full row has been inflated. - */ - protected void preProcessRow() { + /** + * Called automatically in all modes when a full row has been inflated. + */ + protected void preProcessRow() { - } + } - /** - * Callback, must be implemented in callbackMode - *

- * This should use {@link #getRowFilled()} and {@link #getInflatedRow()} to access the row. - *

- * Must return byes of next row, for next callback. - */ - protected int processRowCallback() { - throw new PngjInputException("not implemented"); - } + /** + * Callback, must be implemented in callbackMode + *

+ * This should use {@link #getRowFilled()} and {@link #getInflatedRow()} to + * access the row. + *

+ * Must return byes of next row, for next callback. + */ + protected int processRowCallback() { + throw new PngjInputException("not implemented"); + } - /** - * Callback, to be implemented in callbackMode - *

- * This will be called once to notify state done - */ - protected void processDoneCallback() {} + /** + * Callback, to be implemented in callbackMode + *

+ * This will be called once to notify state done + */ + protected void processDoneCallback() {} - /** - * Inflated buffer. - * - * The effective length is given by {@link #getRowFilled()} - */ - public byte[] getInflatedRow() { - return row; - } + /** + * Inflated buffer. + * + * The effective length is given by {@link #getRowFilled()} + */ + public byte[] getInflatedRow() { + return row; + } - /** - * Should be called after the previous row was processed - *

- * Pass 0 or negative to signal that we are done (not expecting more bytes) - *

- * This resets {@link #rowfilled} - *

- * The - */ - public void prepareForNextRow(int len) { - rowfilled = 0; - rown++; - if (len < 1) { - rowlen = 0; - done(); - } else if (inf.finished()) { - rowlen = 0; - done(); - } else { - state = State.WAITING_FOR_INPUT; - rowlen = len; - if (!callbackMode) - inflateData(); - } - } + /** + * Should be called after the previous row was processed + *

+ * Pass 0 or negative to signal that we are done (not expecting more bytes) + *

+ * This resets {@link #rowfilled} + *

+ * The + */ + public void prepareForNextRow(final int len) { + rowfilled = 0; + rown++; + if (len < 1) { + rowlen = 0; + done(); + } else if (inf.finished()) { + rowlen = 0; + done(); + } else { + state = State.WAITING_FOR_INPUT; + rowlen = len; + if (!callbackMode) + inflateData(); + } + } - /** - * In this state, the object is waiting for more input to deflate. - *

- * Only in this state it's legal to feed this - */ - public boolean isWaitingForMoreInput() { - return state == State.WAITING_FOR_INPUT; - } + /** + * In this state, the object is waiting for more input to deflate. + *

+ * Only in this state it's legal to feed this + */ + public boolean isWaitingForMoreInput() { + return state == State.WAITING_FOR_INPUT; + } - /** - * In this state, the object is waiting the caller to retrieve inflated data - *

- * Effective length: see {@link #getRowFilled()} - */ - public boolean isRowReady() { - return state == State.ROW_READY; - } + /** + * In this state, the object is waiting the caller to retrieve inflated data + *

+ * Effective length: see {@link #getRowFilled()} + */ + public boolean isRowReady() { + return state == State.ROW_READY; + } - /** - * In this state, all relevant data has been uncompressed and retrieved (exceptionally, the reading has ended - * prematurely). - *

- * We can still feed this object, but the bytes will be swallowed/ignored. - */ - public boolean isDone() { - return state.isDone(); - } + /** + * In this state, all relevant data has been uncompressed and retrieved + * (exceptionally, the reading has ended + * prematurely). + *

+ * We can still feed this object, but the bytes will be swallowed/ignored. + */ + public boolean isDone() { + return state.isDone(); + } - public boolean isTerminated() { - return state.isTerminated(); - } + public boolean isTerminated() { + return state.isTerminated(); + } - /** - * This will be called by the owner to report us the next chunk to come. We can make our own internal changes and - * checks. This returns true if we acknowledge the next chunk as part of this set - */ - public boolean ackNextChunkId(String id) { - if (state.isTerminated()) - return false; - else if (id.equals(chunkid)) { - return true; - } else { - if (!allowOtherChunksInBetween(id)) { - if (state.isDone()) { - if (!isTerminated()) - terminate(); - return false; - } else { - throw new PngjInputException("Unexpected chunk " + id + " while " + chunkid - + " set is not done"); - } - } else - return true; - } - } + /** + * This will be called by the owner to report us the next chunk to come. We + * can make our own internal changes and + * checks. This returns true if we acknowledge the next chunk as part of + * this set + */ + public boolean ackNextChunkId(final String id) { + if (state.isTerminated()) + return false; + else if (id.equals(chunkid)) + return true; + else if (!allowOtherChunksInBetween(id)) { + if (state.isDone()) { + if (!isTerminated()) + terminate(); + return false; + } else + throw new PngjInputException("Unexpected chunk " + id + " while " + chunkid + " set is not done"); + } else + return true; + } - protected void terminate() { - close(); - } + protected void terminate() { + close(); + } - /** - * This should be called when discarding this object, or for aborting. Secure, idempotent Don't use this just to - * notify this object that it has no more work to do, see {@link #done()} - * */ - public void close() { - try { - if (!state.isTerminated()) { - state = State.TERMINATED; - } - if (infOwn && inf != null) { - inf.end();// we end the Inflater only if we created it - inf = null; - } - } catch (Exception e) { - } - } + /** + * This should be called when discarding this object, or for aborting. + * Secure, idempotent Don't use this just to + * notify this object that it has no more work to do, see {@link #done()} + */ + public void close() { + try { + if (!state.isTerminated()) + state = State.TERMINATED; + if (infOwn && inf != null) { + inf.end();// we end the Inflater only if we created it + inf = null; + } + } catch (final Exception e) {} + } - /** - * Forces the DONE state, this object won't uncompress more data. It's still not terminated, it will accept more IDAT - * chunks, but will ignore them. - */ - public void done() { - if (!isDone()) - state = State.WORK_DONE; - } + /** + * Forces the DONE state, this object won't uncompress more data. It's still + * not terminated, it will accept more IDAT + * chunks, but will ignore them. + */ + public void done() { + if (!isDone()) + state = State.WORK_DONE; + } - /** - * Target size of the current row, including filter byte.
- * should coincide (or be less than) with row.length - */ - public int getRowLen() { - return rowlen; - } + /** + * Target size of the current row, including filter byte.
+ * should coincide (or be less than) with row.length + */ + public int getRowLen() { + return rowlen; + } - /** This the amount of valid bytes in the buffer */ - public int getRowFilled() { - return rowfilled; - } + /** This the amount of valid bytes in the buffer */ + public int getRowFilled() { + return rowfilled; + } - /** - * Get current (last) row number. - *

- * This corresponds to the raw numeration of rows as seen by the deflater. Not the same as the real image row, if - * interlaced. - * - */ - public int getRown() { - return rown; - } + /** + * Get current (last) row number. + *

+ * This corresponds to the raw numeration of rows as seen by the deflater. + * Not the same as the real image row, if + * interlaced. + * + */ + public int getRown() { + return rown; + } - /** - * Some IDAT-like set can allow other chunks in between (APGN?). - *

- * Normally false. - * - * @param id Id of the other chunk that appeared in middel of this set. - * @return true if allowed - */ - public boolean allowOtherChunksInBetween(String id) { - return false; - } + /** + * Some IDAT-like set can allow other chunks in between (APGN?). + *

+ * Normally false. + * + * @param id + * Id of the other chunk that appeared in middel of this set. + * @return true if allowed + */ + public boolean allowOtherChunksInBetween(final String id) { + return false; + } - /** - * Callback mode = async processing - */ - public boolean isCallbackMode() { - return callbackMode; - } + /** + * Callback mode = async processing + */ + public boolean isCallbackMode() { + return callbackMode; + } - public void setCallbackMode(boolean callbackMode) { - this.callbackMode = callbackMode; - } + public void setCallbackMode(final boolean callbackMode) { + this.callbackMode = callbackMode; + } - /** total number of bytes that have been fed to this object */ - public long getBytesIn() { - return nBytesIn; - } + /** total number of bytes that have been fed to this object */ + public long getBytesIn() { + return nBytesIn; + } - /** total number of bytes that have been uncompressed */ - public long getBytesOut() { - return nBytesOut; - } + /** total number of bytes that have been uncompressed */ + public long getBytesOut() { + return nBytesOut; + } - @Override - public String toString() { - StringBuilder sb = - new StringBuilder("idatSet : " + curChunk.getChunkRaw().id + " state=" + state + " rows=" - + rown + " bytes=" + nBytesIn + "/" + nBytesOut); - return sb.toString(); - } + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("idatSet : " + curChunk.getChunkRaw().id + " state=" + state + " rows=" + rown + " bytes=" + nBytesIn + "/" + nBytesOut); + return sb.toString(); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/Deinterlacer.java b/teavm/src/main/java/ar/com/hjg/pngj/Deinterlacer.java index ffb7260c..b9c895b7 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/Deinterlacer.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/Deinterlacer.java @@ -1,199 +1,197 @@ package ar.com.hjg.pngj; public class Deinterlacer { - final ImageInfo imi; - private int pass; // 1-7 - private int rows, cols; - int dY, dX, oY, oX; // current step and offset (in pixels) - int oXsamples, dXsamples; // step in samples + final ImageInfo imi; + private int pass; // 1-7 + private int rows, cols; + int dY, dX, oY, oX; // current step and offset (in pixels) + int oXsamples, dXsamples; // step in samples - // current row in the virtual subsampled image; this increments (by 1) from 0 to rows/dy 7 times - private int currRowSubimg; - // in the real image, this will cycle from 0 to im.rows in different steps, 7 times - private int currRowReal; - private int currRowSeq; // not counting empty rows + // current row in the virtual subsampled image; this increments (by 1) from 0 to rows/dy 7 times + private int currRowSubimg; + // in the real image, this will cycle from 0 to im.rows in different steps, 7 times + private int currRowReal; + private int currRowSeq; // not counting empty rows - int totalRows; - private boolean ended = false; + int totalRows; + private boolean ended = false; - public Deinterlacer(ImageInfo iminfo) { - this.imi = iminfo; - pass = 0; - currRowSubimg = -1; - currRowReal = -1; - currRowSeq = 0; - ended = false; - totalRows = 0; // lazy compute - setPass(1); - setRow(0); - } + public Deinterlacer(final ImageInfo iminfo) { + imi = iminfo; + pass = 0; + currRowSubimg = -1; + currRowReal = -1; + currRowSeq = 0; + ended = false; + totalRows = 0; // lazy compute + setPass(1); + setRow(0); + } - /** this refers to the row currRowSubimg */ - private void setRow(int n) { // This should be called only intercally, in sequential order - currRowSubimg = n; - currRowReal = n * dY + oY; - if (currRowReal < 0 || currRowReal >= imi.rows) - throw new PngjExceptionInternal("bad row - this should not happen"); - } + /** this refers to the row currRowSubimg */ + private void setRow(final int n) { // This should be called only intercally, in sequential order + currRowSubimg = n; + currRowReal = n * dY + oY; + if (currRowReal < 0 || currRowReal >= imi.rows) + throw new PngjExceptionInternal("bad row - this should not happen"); + } - /** Skips passes with no rows. Return false is no more rows */ - boolean nextRow() { - currRowSeq++; - if (rows == 0 || currRowSubimg >= rows - 1) { // next pass - if (pass == 7) { - ended = true; - return false; - } - setPass(pass + 1); - if (rows == 0) { - currRowSeq--; - return nextRow(); - } - setRow(0); - } else { - setRow(currRowSubimg + 1); - } - return true; - } + /** Skips passes with no rows. Return false is no more rows */ + boolean nextRow() { + currRowSeq++; + if (rows == 0 || currRowSubimg >= rows - 1) { // next pass + if (pass == 7) { + ended = true; + return false; + } + setPass(pass + 1); + if (rows == 0) { + currRowSeq--; + return nextRow(); + } + setRow(0); + } else + setRow(currRowSubimg + 1); + return true; + } - boolean isEnded() { - return ended; - } + boolean isEnded() { + return ended; + } - void setPass(int p) { - if (this.pass == p) - return; - pass = p; - byte[] pp = paramsForPass(p);// dx,dy,ox,oy - dX = pp[0]; - dY = pp[1]; - oX = pp[2]; - oY = pp[3]; - rows = imi.rows > oY ? (imi.rows + dY - 1 - oY) / dY : 0; - cols = imi.cols > oX ? (imi.cols + dX - 1 - oX) / dX : 0; - if (cols == 0) - rows = 0; // well, really... - dXsamples = dX * imi.channels; - oXsamples = oX * imi.channels; - } + void setPass(final int p) { + if (pass == p) + return; + pass = p; + final byte[] pp = Deinterlacer.paramsForPass(p);// dx,dy,ox,oy + dX = pp[0]; + dY = pp[1]; + oX = pp[2]; + oY = pp[3]; + rows = imi.rows > oY ? (imi.rows + dY - 1 - oY) / dY : 0; + cols = imi.cols > oX ? (imi.cols + dX - 1 - oX) / dX : 0; + if (cols == 0) + rows = 0; // well, really... + dXsamples = dX * imi.channels; + oXsamples = oX * imi.channels; + } - static byte[] paramsForPass(final int p) {// dx,dy,ox,oy - switch (p) { - case 1: - return new byte[] {8, 8, 0, 0}; - case 2: - return new byte[] {8, 8, 4, 0}; - case 3: - return new byte[] {4, 8, 0, 4}; - case 4: - return new byte[] {4, 4, 2, 0}; - case 5: - return new byte[] {2, 4, 0, 2}; - case 6: - return new byte[] {2, 2, 1, 0}; - case 7: - return new byte[] {1, 2, 0, 1}; - default: - throw new PngjExceptionInternal("bad interlace pass" + p); - } - } + static byte[] paramsForPass(final int p) {// dx,dy,ox,oy + switch (p) { + case 1: + return new byte[] { 8, 8, 0, 0 }; + case 2: + return new byte[] { 8, 8, 4, 0 }; + case 3: + return new byte[] { 4, 8, 0, 4 }; + case 4: + return new byte[] { 4, 4, 2, 0 }; + case 5: + return new byte[] { 2, 4, 0, 2 }; + case 6: + return new byte[] { 2, 2, 1, 0 }; + case 7: + return new byte[] { 1, 2, 0, 1 }; + default: + throw new PngjExceptionInternal("bad interlace pass" + p); + } + } - /** - * current row number inside the "sub image" - */ - int getCurrRowSubimg() { - return currRowSubimg; - } + /** + * current row number inside the "sub image" + */ + int getCurrRowSubimg() { + return currRowSubimg; + } - /** - * current row number inside the "real image" - */ - int getCurrRowReal() { - return currRowReal; - } + /** + * current row number inside the "real image" + */ + int getCurrRowReal() { + return currRowReal; + } - /** - * current pass number (1-7) - */ - int getPass() { - return pass; - } + /** + * current pass number (1-7) + */ + int getPass() { + return pass; + } - /** - * How many rows has the current pass? - **/ - int getRows() { - return rows; - } + /** + * How many rows has the current pass? + **/ + int getRows() { + return rows; + } - /** - * How many columns (pixels) are there in the current row - */ - int getCols() { - return cols; - } + /** + * How many columns (pixels) are there in the current row + */ + int getCols() { + return cols; + } - public int getPixelsToRead() { - return getCols(); - } + public int getPixelsToRead() { + return getCols(); + } - public int getBytesToRead() { // not including filter byte - return (imi.bitspPixel * getPixelsToRead() + 7) / 8; - } + public int getBytesToRead() { // not including filter byte + return (imi.bitspPixel * getPixelsToRead() + 7) / 8; + } - public int getdY() { - return dY; - } + public int getdY() { + return dY; + } - /* - * in pixels - */ - public int getdX() { - return dX; - } + /* + * in pixels + */ + public int getdX() { + return dX; + } - public int getoY() { - return oY; - } + public int getoY() { + return oY; + } - /* - * in pixels - */ - public int getoX() { - return oX; - } + /* + * in pixels + */ + public int getoX() { + return oX; + } - public int getTotalRows() { - if (totalRows == 0) { // lazy compute - for (int p = 1; p <= 7; p++) { - byte[] pp = paramsForPass(p); // dx dy ox oy - int rows = imi.rows > pp[3] ? (imi.rows + pp[1] - 1 - pp[3]) / pp[1] : 0; - int cols = imi.cols > pp[2] ? (imi.cols + pp[0] - 1 - pp[2]) / pp[0] : 0; - if (rows > 0 && cols > 0) - totalRows += rows; - } - } - return totalRows; - } + public int getTotalRows() { + if (totalRows == 0) + for (int p = 1; p <= 7; p++) { + final byte[] pp = Deinterlacer.paramsForPass(p); // dx dy ox oy + final int rows = imi.rows > pp[3] ? (imi.rows + pp[1] - 1 - pp[3]) / pp[1] : 0; + final int cols = imi.cols > pp[2] ? (imi.cols + pp[0] - 1 - pp[2]) / pp[0] : 0; + if (rows > 0 && cols > 0) + totalRows += rows; + } + return totalRows; + } - /** - * total unfiltered bytes in the image, including the filter byte - */ - public long getTotalRawBytes() { // including the filter byte - long bytes = 0; - for (int p = 1; p <= 7; p++) { - byte[] pp = paramsForPass(p); // dx dy ox oy - int rows = imi.rows > pp[3] ? (imi.rows + pp[1] - 1 - pp[3]) / pp[1] : 0; - int cols = imi.cols > pp[2] ? (imi.cols + pp[0] - 1 - pp[2]) / pp[0] : 0; - int bytesr = (imi.bitspPixel * cols + 7) / 8; // without filter byte - if (rows > 0 && cols > 0) - bytes += rows * (1 + (long) bytesr); - } - return bytes; - } + /** + * total unfiltered bytes in the image, including the filter byte + */ + public long getTotalRawBytes() { // including the filter byte + long bytes = 0; + for (int p = 1; p <= 7; p++) { + final byte[] pp = Deinterlacer.paramsForPass(p); // dx dy ox oy + final int rows = imi.rows > pp[3] ? (imi.rows + pp[1] - 1 - pp[3]) / pp[1] : 0; + final int cols = imi.cols > pp[2] ? (imi.cols + pp[0] - 1 - pp[2]) / pp[0] : 0; + final int bytesr = (imi.bitspPixel * cols + 7) / 8; // without filter byte + if (rows > 0 && cols > 0) + bytes += rows * (1 + (long) bytesr); + } + return bytes; + } - public int getCurrRowSeq() { - return currRowSeq; - } + public int getCurrRowSeq() { + return currRowSeq; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/FilterType.java b/teavm/src/main/java/ar/com/hjg/pngj/FilterType.java index 66128b75..b71bc6e6 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/FilterType.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/FilterType.java @@ -4,121 +4,122 @@ import java.util.HashMap; /** * Internal PNG predictor filter type - * - * Negative values are pseudo types, actually global strategies for writing, that (can) result on different real filters + * + * Negative values are pseudo types, actually global strategies for writing, + * that (can) result on different real filters * for different rows */ public enum FilterType { - /** - * No filter. - */ - FILTER_NONE(0), - /** - * SUB filter (uses same row) - */ - FILTER_SUB(1), - /** - * UP filter (uses previous row) - */ - FILTER_UP(2), - /** - * AVERAGE filter - */ - FILTER_AVERAGE(3), - /** - * PAETH predictor - */ - FILTER_PAETH(4), - /** - * Default strategy: select one of the standard filters depending on global image parameters - */ - FILTER_DEFAULT(-1), - /** - * @deprecated use #FILTER_ADAPTIVE_FAST - */ - FILTER_AGGRESSIVE(-2), - /** - * @deprecated use #FILTER_ADAPTIVE_MEDIUM or #FILTER_ADAPTIVE_FULL - */ - FILTER_VERYAGGRESSIVE(-4), - /** - * Adaptative strategy, sampling each row, or almost - */ - FILTER_ADAPTIVE_FULL(-4), - /** - * Adaptive strategy, skippping some rows - */ - FILTER_ADAPTIVE_MEDIUM(-3), // samples about 1/4 row - /** - * Adaptative strategy, skipping many rows - more speed - */ - FILTER_ADAPTIVE_FAST(-2), // samples each 8 or 16 rows - /** - * Experimental - */ - FILTER_SUPER_ADAPTIVE(-10), // - /** - * Preserves the filter passed in original row. - */ - FILTER_PRESERVE(-40), - /** - * Uses all fiters, one for lines, cyciclally. Only for tests. - */ - FILTER_CYCLIC(-50), - /** - * Not specified, placeholder for unknown or NA filters. - */ - FILTER_UNKNOWN(-100); + /** + * No filter. + */ + FILTER_NONE(0), + /** + * SUB filter (uses same row) + */ + FILTER_SUB(1), + /** + * UP filter (uses previous row) + */ + FILTER_UP(2), + /** + * AVERAGE filter + */ + FILTER_AVERAGE(3), + /** + * PAETH predictor + */ + FILTER_PAETH(4), + /** + * Default strategy: select one of the standard filters depending on global + * image parameters + */ + FILTER_DEFAULT(-1), + /** + * @deprecated use #FILTER_ADAPTIVE_FAST + */ + FILTER_AGGRESSIVE(-2), + /** + * @deprecated use #FILTER_ADAPTIVE_MEDIUM or #FILTER_ADAPTIVE_FULL + */ + FILTER_VERYAGGRESSIVE(-4), + /** + * Adaptative strategy, sampling each row, or almost + */ + FILTER_ADAPTIVE_FULL(-4), + /** + * Adaptive strategy, skippping some rows + */ + FILTER_ADAPTIVE_MEDIUM(-3), // samples about 1/4 row + /** + * Adaptative strategy, skipping many rows - more speed + */ + FILTER_ADAPTIVE_FAST(-2), // samples each 8 or 16 rows + /** + * Experimental + */ + FILTER_SUPER_ADAPTIVE(-10), // + /** + * Preserves the filter passed in original row. + */ + FILTER_PRESERVE(-40), + /** + * Uses all fiters, one for lines, cyciclally. Only for tests. + */ + FILTER_CYCLIC(-50), + /** + * Not specified, placeholder for unknown or NA filters. + */ + FILTER_UNKNOWN(-100); - public final int val; + public final int val; - private FilterType(int val) { - this.val = val; - } + private FilterType(final int val) { + this.val = val; + } - private static HashMap byVal; + private static HashMap byVal; - static { - byVal = new HashMap(); - for (FilterType ft : values()) { - byVal.put(ft.val, ft); - } - } + static { + FilterType.byVal = new HashMap<>(); + for (final FilterType ft : FilterType.values()) + FilterType.byVal.put(ft.val, ft); + } - public static FilterType getByVal(int i) { - return byVal.get(i); - } + public static FilterType getByVal(final int i) { + return FilterType.byVal.get(i); + } - /** only considers standard */ - public static boolean isValidStandard(int i) { - return i >= 0 && i <= 4; - } + /** only considers standard */ + public static boolean isValidStandard(final int i) { + return i >= 0 && i <= 4; + } - public static boolean isValidStandard(FilterType fy) { - return fy != null && isValidStandard(fy.val); - } + public static boolean isValidStandard(final FilterType fy) { + return fy != null && FilterType.isValidStandard(fy.val); + } - public static boolean isAdaptive(FilterType fy) { - return fy.val <= -2 && fy.val >= -4; - } + public static boolean isAdaptive(final FilterType fy) { + return fy.val <= -2 && fy.val >= -4; + } - /** - * Returns all "standard" filters - */ - public static FilterType[] getAllStandard() { - return new FilterType[] {FILTER_NONE, FILTER_SUB, FILTER_UP, FILTER_AVERAGE, FILTER_PAETH}; - } + /** + * Returns all "standard" filters + */ + public static FilterType[] getAllStandard() { + return new FilterType[] { FILTER_NONE, FILTER_SUB, FILTER_UP, FILTER_AVERAGE, FILTER_PAETH }; + } - public static FilterType[] getAllStandardNoneLast() { - return new FilterType[] {FILTER_SUB, FILTER_UP, FILTER_AVERAGE, FILTER_PAETH, FILTER_NONE}; - } + public static FilterType[] getAllStandardNoneLast() { + return new FilterType[] { FILTER_SUB, FILTER_UP, FILTER_AVERAGE, FILTER_PAETH, FILTER_NONE }; + } - public static FilterType[] getAllStandardExceptNone() { - return new FilterType[] {FILTER_SUB, FILTER_UP, FILTER_AVERAGE, FILTER_PAETH}; - } + public static FilterType[] getAllStandardExceptNone() { + return new FilterType[] { FILTER_SUB, FILTER_UP, FILTER_AVERAGE, FILTER_PAETH }; + } - static FilterType[] getAllStandardForFirstRow() { - return new FilterType[] {FILTER_SUB, FILTER_NONE}; - } + static FilterType[] getAllStandardForFirstRow() { + return new FilterType[] { FILTER_SUB, FILTER_NONE }; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/IBytesConsumer.java b/teavm/src/main/java/ar/com/hjg/pngj/IBytesConsumer.java index b2fcde3e..bba345f6 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/IBytesConsumer.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/IBytesConsumer.java @@ -1,14 +1,16 @@ package ar.com.hjg.pngj; /** - * Bytes consumer. Objects implementing this interface can act as bytes consumers, that are "fed" with bytes. + * Bytes consumer. Objects implementing this interface can act as bytes + * consumers, that are "fed" with bytes. */ public interface IBytesConsumer { - /** - * Eats some bytes, at most len. - *

- * Returns bytes actually consumed. A negative return value signals that the consumer is done, it refuses to eat more - * bytes. This should only return 0 if len is 0 - */ - int consume(byte[] buf, int offset, int len); + /** + * Eats some bytes, at most len. + *

+ * Returns bytes actually consumed. A negative return value signals that the + * consumer is done, it refuses to eat more + * bytes. This should only return 0 if len is 0 + */ + int consume(byte[] buf, int offset, int len); } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/IChunkFactory.java b/teavm/src/main/java/ar/com/hjg/pngj/IChunkFactory.java index 013f3628..4e0f814d 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/IChunkFactory.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/IChunkFactory.java @@ -10,11 +10,14 @@ import ar.com.hjg.pngj.chunks.PngChunk; */ public interface IChunkFactory { - /** - * @param chunkRaw Chunk in raw form. Data can be null if it was skipped or processed directly (eg IDAT) - * @param imgInfo Not normally necessary, but some chunks want this info - * @return should never return null. - */ - public PngChunk createChunk(ChunkRaw chunkRaw, ImageInfo imgInfo); + /** + * @param chunkRaw + * Chunk in raw form. Data can be null if it was skipped or + * processed directly (eg IDAT) + * @param imgInfo + * Not normally necessary, but some chunks want this info + * @return should never return null. + */ + PngChunk createChunk(ChunkRaw chunkRaw, ImageInfo imgInfo); } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/IDatChunkWriter.java b/teavm/src/main/java/ar/com/hjg/pngj/IDatChunkWriter.java index e314193c..f3c7d0c6 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/IDatChunkWriter.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/IDatChunkWriter.java @@ -6,124 +6,127 @@ import ar.com.hjg.pngj.chunks.ChunkHelper; import ar.com.hjg.pngj.chunks.ChunkRaw; /** - * Outputs a sequence of IDAT-like chunk, that is filled progressively until the max chunk length is reached (or until + * Outputs a sequence of IDAT-like chunk, that is filled progressively until the + * max chunk length is reached (or until * flush()) */ public class IDatChunkWriter { - private static final int MAX_LEN_DEFAULT = 32768; // 32K rather arbitrary - data only + private static final int MAX_LEN_DEFAULT = 32768; // 32K rather arbitrary - data only - private final OutputStream outputStream; - private final int maxChunkLen; - private byte[] buf; + private final OutputStream outputStream; + private final int maxChunkLen; + private byte[] buf; - private int offset = 0; - private int availLen; - private long totalBytesWriten = 0; // including header+crc - private int chunksWriten = 0; + private int offset = 0; + private int availLen; + private long totalBytesWriten = 0; // including header+crc + private int chunksWriten = 0; - public IDatChunkWriter(OutputStream outputStream) { - this(outputStream, 0); - } + public IDatChunkWriter(final OutputStream outputStream) { + this(outputStream, 0); + } - public IDatChunkWriter(OutputStream outputStream, int maxChunkLength) { - this.outputStream = outputStream; - this.maxChunkLen = maxChunkLength > 0 ? maxChunkLength : MAX_LEN_DEFAULT; - buf = new byte[maxChunkLen]; - availLen = maxChunkLen - offset; - postReset(); - } + public IDatChunkWriter(final OutputStream outputStream, final int maxChunkLength) { + this.outputStream = outputStream; + maxChunkLen = maxChunkLength > 0 ? maxChunkLength : IDatChunkWriter.MAX_LEN_DEFAULT; + buf = new byte[maxChunkLen]; + availLen = maxChunkLen - offset; + postReset(); + } - public IDatChunkWriter(OutputStream outputStream, byte[] b) { - this.outputStream = outputStream; - this.buf = b != null ? b : new byte[MAX_LEN_DEFAULT]; - this.maxChunkLen = b.length; - availLen = maxChunkLen - offset; - postReset(); - } + public IDatChunkWriter(final OutputStream outputStream, final byte[] b) { + this.outputStream = outputStream; + buf = b != null ? b : new byte[IDatChunkWriter.MAX_LEN_DEFAULT]; + maxChunkLen = b.length; + availLen = maxChunkLen - offset; + postReset(); + } - protected byte[] getChunkId() { - return ChunkHelper.b_IDAT; - } + protected byte[] getChunkId() { + return ChunkHelper.b_IDAT; + } - /** - * Writes a chhunk if there is more than minLenToWrite. - * - * This is normally called internally, but can be called explicitly to force flush. - */ - public final void flush() { - if (offset > 0 && offset >= minLenToWrite()) { - ChunkRaw c = new ChunkRaw(offset, getChunkId(), false); - c.data = buf; - c.writeChunk(outputStream); - totalBytesWriten += c.len + 12; - chunksWriten++; - offset = 0; - availLen = maxChunkLen; - postReset(); - } - } + /** + * Writes a chhunk if there is more than minLenToWrite. + * + * This is normally called internally, but can be called explicitly to force + * flush. + */ + public final void flush() { + if (offset > 0 && offset >= minLenToWrite()) { + final ChunkRaw c = new ChunkRaw(offset, getChunkId(), false); + c.data = buf; + c.writeChunk(outputStream); + totalBytesWriten += c.len + 12; + chunksWriten++; + offset = 0; + availLen = maxChunkLen; + postReset(); + } + } - public int getOffset() { - return offset; - } + public int getOffset() { + return offset; + } - public int getAvailLen() { - return availLen; - } + public int getAvailLen() { + return availLen; + } - /** triggers an flush+reset if appropiate */ - public void incrementOffset(int n) { - offset += n; - availLen -= n; - if (availLen < 0) - throw new PngjOutputException("Anomalous situation"); - if (availLen == 0) { - flush(); - } - } + /** triggers an flush+reset if appropiate */ + public void incrementOffset(final int n) { + offset += n; + availLen -= n; + if (availLen < 0) + throw new PngjOutputException("Anomalous situation"); + if (availLen == 0) + flush(); + } - /** - * this should rarely be used, the normal way (to avoid double copying) is to get the buffer and write directly to it - */ - public void write(byte[] b, int o, int len) { - while (len > 0) { - int n = len <= availLen ? len : availLen; - System.arraycopy(b, o, buf, offset, n); - incrementOffset(n); - len -= n; - o += n; - } - } + /** + * this should rarely be used, the normal way (to avoid double copying) is + * to get the buffer and write directly to it + */ + public void write(final byte[] b, int o, int len) { + while (len > 0) { + final int n = len <= availLen ? len : availLen; + System.arraycopy(b, o, buf, offset, n); + incrementOffset(n); + len -= n; + o += n; + } + } - /** this will be called after reset */ - protected void postReset() { - // fdat could override this (and minLenToWrite) to add a prefix - } + /** this will be called after reset */ + protected void postReset() { + // fdat could override this (and minLenToWrite) to add a prefix + } - protected int minLenToWrite() { - return 1; - } + protected int minLenToWrite() { + return 1; + } - public void close() { - flush(); - offset = 0; - buf = null; - } + public void close() { + flush(); + offset = 0; + buf = null; + } - /** - * You can write directly to this buffer, using {@link #getOffset()} and {@link #getAvailLen()}. You should call - * {@link #incrementOffset(int)} inmediately after. - * */ - public byte[] getBuf() { - return buf; - } + /** + * You can write directly to this buffer, using {@link #getOffset()} and + * {@link #getAvailLen()}. You should call + * {@link #incrementOffset(int)} inmediately after. + */ + public byte[] getBuf() { + return buf; + } - public long getTotalBytesWriten() { - return totalBytesWriten; - } + public long getTotalBytesWriten() { + return totalBytesWriten; + } - public int getChunksWriten() { - return chunksWriten; - } + public int getChunksWriten() { + return chunksWriten; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/IImageLine.java b/teavm/src/main/java/ar/com/hjg/pngj/IImageLine.java index f40f13d0..c1275194 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/IImageLine.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/IImageLine.java @@ -3,39 +3,48 @@ package ar.com.hjg.pngj; /** * General format-translated image line. *

- * The methods from this interface provides translation from/to PNG raw unfiltered pixel data, for each image line. This + * The methods from this interface provides translation from/to PNG raw + * unfiltered pixel data, for each image line. This * doesn't make any assumptions of underlying storage. *

- * The user of this library will not normally use this methods, but instead will cast to a more concrete implementation, - * as {@link ImageLineInt} or {@link ImageLineByte} with its methods for accessing the pixel values. + * The user of this library will not normally use this methods, but instead will + * cast to a more concrete implementation, + * as {@link ImageLineInt} or {@link ImageLineByte} with its methods for + * accessing the pixel values. */ public interface IImageLine { - /** - * Extract pixels from a raw unlfilterd PNG row. Len is the total amount of bytes in the array, including the first - * byte (filter type) - * - * Arguments offset and step (0 and 1 for non interlaced) are in PIXELS. It's guaranteed that when step==1 then - * offset=0 - * - * Notice that when step!=1 the data is partial, this method will be called several times - * - * Warning: the data in array 'raw' starts at position 0 and has 'len' consecutive bytes. 'offset' and 'step' refer to - * the pixels in destination - */ - void readFromPngRaw(byte[] raw, int len, int offset, int step); + /** + * Extract pixels from a raw unlfilterd PNG row. Len is the total amount of + * bytes in the array, including the first + * byte (filter type) + * + * Arguments offset and step (0 and 1 for non interlaced) are in PIXELS. + * It's guaranteed that when step==1 then + * offset=0 + * + * Notice that when step!=1 the data is partial, this method will be called + * several times + * + * Warning: the data in array 'raw' starts at position 0 and has 'len' + * consecutive bytes. 'offset' and 'step' refer to + * the pixels in destination + */ + void readFromPngRaw(byte[] raw, int len, int offset, int step); - /** - * This is called when the read for the line has been completed (eg for interlaced). It's called exactly once for each - * line. This is provided in case the class needs to to some postprocessing. - */ - void endReadFromPngRaw(); + /** + * This is called when the read for the line has been completed (eg for + * interlaced). It's called exactly once for each + * line. This is provided in case the class needs to to some postprocessing. + */ + void endReadFromPngRaw(); - /** - * Writes the line to a PNG raw byte array, in the unfiltered PNG format Notice that the first byte is the filter - * type, you should write it only if you know it. - * - */ - void writeToPngRaw(byte[] raw); + /** + * Writes the line to a PNG raw byte array, in the unfiltered PNG format + * Notice that the first byte is the filter + * type, you should write it only if you know it. + * + */ + void writeToPngRaw(byte[] raw); } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/IImageLineArray.java b/teavm/src/main/java/ar/com/hjg/pngj/IImageLineArray.java index 6d3d6691..3b2fdfa8 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/IImageLineArray.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/IImageLineArray.java @@ -1,23 +1,26 @@ package ar.com.hjg.pngj; /** - * This interface is just for the sake of unifying some methods of {@link ImageLineHelper} that can use both - * {@link ImageLineInt} or {@link ImageLineByte}. It's not very useful outside that, and the user should not rely much + * This interface is just for the sake of unifying some methods of + * {@link ImageLineHelper} that can use both + * {@link ImageLineInt} or {@link ImageLineByte}. It's not very useful outside + * that, and the user should not rely much * on this. */ public interface IImageLineArray { - public ImageInfo getImageInfo(); + ImageInfo getImageInfo(); - public FilterType getFilterType(); + FilterType getFilterType(); - /** - * length of array (should correspond to samples) - */ - public int getSize(); + /** + * length of array (should correspond to samples) + */ + int getSize(); - /** - * Get i-th element of array (for 0 to size-1). The meaning of this is type dependent. For ImageLineInt and - * ImageLineByte is the sample value. - */ - public int getElem(int i); + /** + * Get i-th element of array (for 0 to size-1). The meaning of this is type + * dependent. For ImageLineInt and + * ImageLineByte is the sample value. + */ + int getElem(int i); } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/IImageLineFactory.java b/teavm/src/main/java/ar/com/hjg/pngj/IImageLineFactory.java index 1c0a4bd2..aaf4202a 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/IImageLineFactory.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/IImageLineFactory.java @@ -4,5 +4,5 @@ package ar.com.hjg.pngj; * Image Line factory. */ public interface IImageLineFactory { - public T createImageLine(ImageInfo iminfo); + T createImageLine(ImageInfo iminfo); } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/IImageLineSet.java b/teavm/src/main/java/ar/com/hjg/pngj/IImageLineSet.java index 595001aa..6c4b659d 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/IImageLineSet.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/IImageLineSet.java @@ -1,53 +1,64 @@ package ar.com.hjg.pngj; - /** * Set of {@link IImageLine} elements. *

- * This is actually a "virtual" set, it can be implemented in several ways; for example + * This is actually a "virtual" set, it can be implemented in several ways; for + * example *

    - *
  • Cursor-like: stores only one line, which is implicitly moved when requested
  • + *
  • Cursor-like: stores only one line, which is implicitly moved when + * requested
  • *
  • All lines: all lines stored as an array of IImageLine
  • *
  • - * Subset of lines: eg, only first 3 lines, or odd numbered lines. Or a band of neighbours lines that is moved like a + * Subset of lines: eg, only first 3 lines, or odd numbered lines. Or a band of + * neighbours lines that is moved like a * cursor.
  • - * The ImageLine that PngReader returns is hosted by a IImageLineSet (this abstraction allows the implementation to deal - * with interlaced images cleanly) but the library user does not normally needs to know that (or rely on that), except + * The ImageLine that PngReader returns is hosted by a IImageLineSet (this + * abstraction allows the implementation to deal + * with interlaced images cleanly) but the library user does not normally needs + * to know that (or rely on that), except * for the {@link PngReader#readRows()} method. *
*/ public interface IImageLineSet { - /** - * Asks for imageline corresponding to row n in the original image (zero based). This can trigger side - * effects in this object (eg, advance a cursor, set current row number...) In some scenarios, this should be consider - * as alias to (pseudocode) positionAtLine(n); getCurrentLine(); - *

- * Throws exception if not available. The caller is supposed to know what he/she is doing - **/ - public IImageLine getImageLine(int n); + /** + * Asks for imageline corresponding to row n in the original image + * (zero based). This can trigger side + * effects in this object (eg, advance a cursor, set current row number...) + * In some scenarios, this should be consider + * as alias to (pseudocode) positionAtLine(n); getCurrentLine(); + *

+ * Throws exception if not available. The caller is supposed to know what + * he/she is doing + **/ + IImageLine getImageLine(int n); - /** - * Like {@link #getImageLine(int)} but uses the raw numbering inside the LineSet This makes little sense for a cursor - * - * @param n Should normally go from 0 to {@link #size()} - * @return - */ - public IImageLine getImageLineRawNum(int n); + /** + * Like {@link #getImageLine(int)} but uses the raw numbering inside the + * LineSet This makes little sense for a cursor + * + * @param n + * Should normally go from 0 to {@link #size()} + * @return + */ + IImageLine getImageLineRawNum(int n); + /** + * Returns true if the set contain row n (in the original + * image,zero based) currently allocated. + *

+ * If it's a single-cursor, this should return true only if it's positioned + * there. (notice that hasImageLine(n) can + * return false, but getImageLine(n) can be ok) + * + **/ + boolean hasImageLine(int n); - /** - * Returns true if the set contain row n (in the original image,zero based) currently allocated. - *

- * If it's a single-cursor, this should return true only if it's positioned there. (notice that hasImageLine(n) can - * return false, but getImageLine(n) can be ok) - * - **/ - public boolean hasImageLine(int n); - - /** - * Internal size of allocated rows This is informational, it should rarely be important for the caller. - **/ - public int size(); + /** + * Internal size of allocated rows This is informational, it should rarely + * be important for the caller. + **/ + int size(); } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/IImageLineSetFactory.java b/teavm/src/main/java/ar/com/hjg/pngj/IImageLineSetFactory.java index e9aeba50..821dd6fe 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/IImageLineSetFactory.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/IImageLineSetFactory.java @@ -3,22 +3,30 @@ package ar.com.hjg.pngj; /** * Factory of {@link IImageLineSet}, used by {@link PngReader}. *

- * - * @param Generic type of IImageLine + * + * @param + * Generic type of IImageLine */ public interface IImageLineSetFactory { - /** - * Creates a new {@link IImageLineSet} - * - * If singleCursor=true, the caller will read and write one row fully at a time, in order (it'll never try to read out - * of order lines), so the implementation can opt for allocate only one line. - * - * @param imgInfo Image info - * @param singleCursor : will read/write one row at a time - * @param nlines : how many lines we plan to read - * @param noffset : how many lines we want to skip from the original image (normally 0) - * @param step : row step (normally 1) - */ - public IImageLineSet create(ImageInfo imgInfo, boolean singleCursor, int nlines, int noffset, - int step); + /** + * Creates a new {@link IImageLineSet} + * + * If singleCursor=true, the caller will read and write one row fully at a + * time, in order (it'll never try to read out + * of order lines), so the implementation can opt for allocate only one + * line. + * + * @param imgInfo + * Image info + * @param singleCursor + * : will read/write one row at a time + * @param nlines + * : how many lines we plan to read + * @param noffset + * : how many lines we want to skip from the original image + * (normally 0) + * @param step + * : row step (normally 1) + */ + IImageLineSet create(ImageInfo imgInfo, boolean singleCursor, int nlines, int noffset, int step); } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/IPngWriterFactory.java b/teavm/src/main/java/ar/com/hjg/pngj/IPngWriterFactory.java index 617f5855..c8c464e5 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/IPngWriterFactory.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/IPngWriterFactory.java @@ -3,5 +3,5 @@ package ar.com.hjg.pngj; import java.io.OutputStream; public interface IPngWriterFactory { - public PngWriter createPngWriter(OutputStream outputStream, ImageInfo imgInfo); + PngWriter createPngWriter(OutputStream outputStream, ImageInfo imgInfo); } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/IdatSet.java b/teavm/src/main/java/ar/com/hjg/pngj/IdatSet.java index 82d83a11..cd0c49d5 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/IdatSet.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/IdatSet.java @@ -7,236 +7,240 @@ import java.util.zip.Inflater; /** * This object process the concatenation of IDAT chunks. *

- * It extends {@link DeflatedChunksSet}, adding the intelligence to unfilter rows, and to understand row lenghts in + * It extends {@link DeflatedChunksSet}, adding the intelligence to unfilter + * rows, and to understand row lenghts in * terms of ImageInfo and (eventually) Deinterlacer */ public class IdatSet extends DeflatedChunksSet { - protected byte rowUnfiltered[]; - protected byte rowUnfilteredPrev[]; - protected final ImageInfo imgInfo; // in the case of APNG this is the frame image - protected final Deinterlacer deinterlacer; + protected byte rowUnfiltered[]; + protected byte rowUnfilteredPrev[]; + protected final ImageInfo imgInfo; // in the case of APNG this is the frame image + protected final Deinterlacer deinterlacer; - final RowInfo rowinfo; // info for the last processed row, for debug + final RowInfo rowinfo; // info for the last processed row, for debug - protected int filterUseStat[] = new int[5]; // for stats + protected int filterUseStat[] = new int[5]; // for stats - /** - * @param id Chunk id (first chunk), should be shared by all concatenated chunks - * @param iminfo Image info - * @param deinterlacer Not null if interlaced - */ - public IdatSet(String id, ImageInfo iminfo, Deinterlacer deinterlacer) { - this(id, iminfo, deinterlacer, null, null); - } + /** + * @param id + * Chunk id (first chunk), should be shared by all concatenated + * chunks + * @param iminfo + * Image info + * @param deinterlacer + * Not null if interlaced + */ + public IdatSet(final String id, final ImageInfo iminfo, final Deinterlacer deinterlacer) { + this(id, iminfo, deinterlacer, null, null); + } - /** - * Special constructor with preallocated buffer. - *

- *

- * Same as {@link #IdatSet(String, ImageInfo, Deinterlacer)}, but you can pass a Inflater (will be reset internally), - * and a buffer (will be used only if size is enough) - */ - public IdatSet(String id, ImageInfo iminfo, Deinterlacer deinterlacer, Inflater inf, byte[] buffer) { - super(id, deinterlacer != null ? deinterlacer.getBytesToRead() + 1 : iminfo.bytesPerRow + 1, - iminfo.bytesPerRow + 1, inf, buffer); - this.imgInfo = iminfo; - this.deinterlacer = deinterlacer; - this.rowinfo = new RowInfo(iminfo, deinterlacer); - } + /** + * Special constructor with preallocated buffer. + *

+ *

+ * Same as {@link #IdatSet(String, ImageInfo, Deinterlacer)}, but you can + * pass a Inflater (will be reset internally), + * and a buffer (will be used only if size is enough) + */ + public IdatSet(final String id, final ImageInfo iminfo, final Deinterlacer deinterlacer, final Inflater inf, final byte[] buffer) { + super(id, deinterlacer != null ? deinterlacer.getBytesToRead() + 1 : iminfo.bytesPerRow + 1, iminfo.bytesPerRow + 1, inf, buffer); + imgInfo = iminfo; + this.deinterlacer = deinterlacer; + rowinfo = new RowInfo(iminfo, deinterlacer); + } - /** - * Applies PNG un-filter to inflated raw line. Result in {@link #getUnfilteredRow()} {@link #getRowLen()} - */ - public void unfilterRow() { - unfilterRow(rowinfo.bytesRow); - } + /** + * Applies PNG un-filter to inflated raw line. Result in + * {@link #getUnfilteredRow()} {@link #getRowLen()} + */ + public void unfilterRow() { + unfilterRow(rowinfo.bytesRow); + } - // nbytes: NOT including the filter byte. leaves result in rowUnfiltered - protected void unfilterRow(int nbytes) { - if (rowUnfiltered == null || rowUnfiltered.length < row.length) { - rowUnfiltered = new byte[row.length]; - rowUnfilteredPrev = new byte[row.length]; - } - if (rowinfo.rowNsubImg == 0) - Arrays.fill(rowUnfiltered, (byte) 0); // see swap that follows - // swap - byte[] tmp = rowUnfiltered; - rowUnfiltered = rowUnfilteredPrev; - rowUnfilteredPrev = tmp; + // nbytes: NOT including the filter byte. leaves result in rowUnfiltered + protected void unfilterRow(final int nbytes) { + if (rowUnfiltered == null || rowUnfiltered.length < row.length) { + rowUnfiltered = new byte[row.length]; + rowUnfilteredPrev = new byte[row.length]; + } + if (rowinfo.rowNsubImg == 0) + Arrays.fill(rowUnfiltered, (byte) 0); // see swap that follows + // swap + final byte[] tmp = rowUnfiltered; + rowUnfiltered = rowUnfilteredPrev; + rowUnfilteredPrev = tmp; - int ftn = row[0]; - if (!FilterType.isValidStandard(ftn)) - throw new PngjInputException("Filter type " + ftn + " invalid"); - FilterType ft = FilterType.getByVal(ftn); - filterUseStat[ftn]++; - rowUnfiltered[0] = row[0]; // we copy the filter type, can be useful - switch (ft) { - case FILTER_NONE: - unfilterRowNone(nbytes); - break; - case FILTER_SUB: - unfilterRowSub(nbytes); - break; - case FILTER_UP: - unfilterRowUp(nbytes); - break; - case FILTER_AVERAGE: - unfilterRowAverage(nbytes); - break; - case FILTER_PAETH: - unfilterRowPaeth(nbytes); - break; - default: - throw new PngjInputException("Filter type " + ftn + " not implemented"); - } - } + final int ftn = row[0]; + if (!FilterType.isValidStandard(ftn)) + throw new PngjInputException("Filter type " + ftn + " invalid"); + final FilterType ft = FilterType.getByVal(ftn); + filterUseStat[ftn]++; + rowUnfiltered[0] = row[0]; // we copy the filter type, can be useful + switch (ft) { + case FILTER_NONE: + unfilterRowNone(nbytes); + break; + case FILTER_SUB: + unfilterRowSub(nbytes); + break; + case FILTER_UP: + unfilterRowUp(nbytes); + break; + case FILTER_AVERAGE: + unfilterRowAverage(nbytes); + break; + case FILTER_PAETH: + unfilterRowPaeth(nbytes); + break; + default: + throw new PngjInputException("Filter type " + ftn + " not implemented"); + } + } - private void unfilterRowAverage(final int nbytes) { - int i, j, x; - for (j = 1 - imgInfo.bytesPixel, i = 1; i <= nbytes; i++, j++) { - x = j > 0 ? (rowUnfiltered[j] & 0xff) : 0; - rowUnfiltered[i] = (byte) (row[i] + (x + (rowUnfilteredPrev[i] & 0xFF)) / 2); - } - } + private void unfilterRowAverage(final int nbytes) { + int i, j, x; + for (j = 1 - imgInfo.bytesPixel, i = 1; i <= nbytes; i++, j++) { + x = j > 0 ? rowUnfiltered[j] & 0xff : 0; + rowUnfiltered[i] = (byte) (row[i] + (x + (rowUnfilteredPrev[i] & 0xFF)) / 2); + } + } - private void unfilterRowNone(final int nbytes) { - for (int i = 1; i <= nbytes; i++) { - rowUnfiltered[i] = (byte) (row[i]); - } - } + private void unfilterRowNone(final int nbytes) { + for (int i = 1; i <= nbytes; i++) + rowUnfiltered[i] = row[i]; + } - private void unfilterRowPaeth(final int nbytes) { - int i, j, x, y; - for (j = 1 - imgInfo.bytesPixel, i = 1; i <= nbytes; i++, j++) { - x = j > 0 ? (rowUnfiltered[j] & 0xFF) : 0; - y = j > 0 ? (rowUnfilteredPrev[j] & 0xFF) : 0; - rowUnfiltered[i] = - (byte) (row[i] + PngHelperInternal - .filterPaethPredictor(x, rowUnfilteredPrev[i] & 0xFF, y)); - } - } + private void unfilterRowPaeth(final int nbytes) { + int i, j, x, y; + for (j = 1 - imgInfo.bytesPixel, i = 1; i <= nbytes; i++, j++) { + x = j > 0 ? rowUnfiltered[j] & 0xFF : 0; + y = j > 0 ? rowUnfilteredPrev[j] & 0xFF : 0; + rowUnfiltered[i] = (byte) (row[i] + PngHelperInternal.filterPaethPredictor(x, rowUnfilteredPrev[i] & 0xFF, y)); + } + } - private void unfilterRowSub(final int nbytes) { - int i, j; - for (i = 1; i <= imgInfo.bytesPixel; i++) { - rowUnfiltered[i] = (byte) (row[i]); - } - for (j = 1, i = imgInfo.bytesPixel + 1; i <= nbytes; i++, j++) { - rowUnfiltered[i] = (byte) (row[i] + rowUnfiltered[j]); - } - } + private void unfilterRowSub(final int nbytes) { + int i, j; + for (i = 1; i <= imgInfo.bytesPixel; i++) + rowUnfiltered[i] = row[i]; + for (j = 1, i = imgInfo.bytesPixel + 1; i <= nbytes; i++, j++) + rowUnfiltered[i] = (byte) (row[i] + rowUnfiltered[j]); + } - private void unfilterRowUp(final int nbytes) { - for (int i = 1; i <= nbytes; i++) { - rowUnfiltered[i] = (byte) (row[i] + rowUnfilteredPrev[i]); - } - } + private void unfilterRowUp(final int nbytes) { + for (int i = 1; i <= nbytes; i++) + rowUnfiltered[i] = (byte) (row[i] + rowUnfilteredPrev[i]); + } - /** - * does the unfiltering of the inflated row, and updates row info - */ - @Override - protected void preProcessRow() { - super.preProcessRow(); - rowinfo.update(getRown()); - unfilterRow(); - rowinfo.updateBuf(rowUnfiltered, rowinfo.bytesRow + 1); - } + /** + * does the unfiltering of the inflated row, and updates row info + */ + @Override + protected void preProcessRow() { + super.preProcessRow(); + rowinfo.update(getRown()); + unfilterRow(); + rowinfo.updateBuf(rowUnfiltered, rowinfo.bytesRow + 1); + } - /** - * Method for async/callback mode . - *

- * In callback mode will be called as soon as each row is retrieved (inflated and unfiltered), after - * {@link #preProcessRow()} - *

- * This is a dummy implementation (this normally should be overriden) that does nothing more than compute the length - * of next row. - *

- * The return value is essential - *

- * - * @return Length of next row, in bytes (including filter byte), non-positive if done - */ - @Override - protected int processRowCallback() { - int bytesNextRow = advanceToNextRow(); - return bytesNextRow; - } + /** + * Method for async/callback mode . + *

+ * In callback mode will be called as soon as each row is retrieved + * (inflated and unfiltered), after + * {@link #preProcessRow()} + *

+ * This is a dummy implementation (this normally should be overriden) that + * does nothing more than compute the length + * of next row. + *

+ * The return value is essential + *

+ * + * @return Length of next row, in bytes (including filter byte), + * non-positive if done + */ + @Override + protected int processRowCallback() { + final int bytesNextRow = advanceToNextRow(); + return bytesNextRow; + } - @Override - protected void processDoneCallback() { - super.processDoneCallback(); - } + @Override + protected void processDoneCallback() { + super.processDoneCallback(); + } - /** - * Signals that we are done with the previous row, begin reading the next one. - *

- * In polled mode, calls setNextRowLen() - *

- * Warning: after calling this, the unfilterRow is invalid! - * - * @return Returns nextRowLen - */ - public int advanceToNextRow() { - // PngHelperInternal.LOGGER.info("advanceToNextRow"); - int bytesNextRow; - if (deinterlacer == null) { - bytesNextRow = getRown() >= imgInfo.rows - 1 ? 0 : imgInfo.bytesPerRow + 1; - } else { - boolean more = deinterlacer.nextRow(); - bytesNextRow = more ? deinterlacer.getBytesToRead() + 1 : 0; - } - if (!isCallbackMode()) { // in callback mode, setNextRowLen() is called internally - prepareForNextRow(bytesNextRow); - } - return bytesNextRow; - } + /** + * Signals that we are done with the previous row, begin reading the next + * one. + *

+ * In polled mode, calls setNextRowLen() + *

+ * Warning: after calling this, the unfilterRow is invalid! + * + * @return Returns nextRowLen + */ + public int advanceToNextRow() { + // PngHelperInternal.LOGGER.info("advanceToNextRow"); + int bytesNextRow; + if (deinterlacer == null) + bytesNextRow = getRown() >= imgInfo.rows - 1 ? 0 : imgInfo.bytesPerRow + 1; + else { + final boolean more = deinterlacer.nextRow(); + bytesNextRow = more ? deinterlacer.getBytesToRead() + 1 : 0; + } + if (!isCallbackMode()) + prepareForNextRow(bytesNextRow); + return bytesNextRow; + } - public boolean isRowReady() { - return !isWaitingForMoreInput(); + @Override + public boolean isRowReady() { + return !isWaitingForMoreInput(); - } + } - /** - * Unfiltered row. - *

- * This should be called only if {@link #isRowReady()} returns true. - *

- * To get real length, use {@link #getRowLen()} - *

- * - * @return Unfiltered row, includes filter byte - */ - public byte[] getUnfilteredRow() { - return rowUnfiltered; - } + /** + * Unfiltered row. + *

+ * This should be called only if {@link #isRowReady()} returns true. + *

+ * To get real length, use {@link #getRowLen()} + *

+ * + * @return Unfiltered row, includes filter byte + */ + public byte[] getUnfilteredRow() { + return rowUnfiltered; + } - public Deinterlacer getDeinterlacer() { - return deinterlacer; - } + public Deinterlacer getDeinterlacer() { + return deinterlacer; + } - void updateCrcs(Checksum... idatCrcs) { - for (Checksum idatCrca : idatCrcs) - if (idatCrca != null)// just for testing - idatCrca.update(getUnfilteredRow(), 1, getRowFilled() - 1); - } + void updateCrcs(final Checksum... idatCrcs) { + for (final Checksum idatCrca : idatCrcs) + if (idatCrca != null)// just for testing + idatCrca.update(getUnfilteredRow(), 1, getRowFilled() - 1); + } - @Override - public void close() { - super.close(); - rowUnfiltered = null;// not really necessary... - rowUnfilteredPrev = null; - } - - /** - * Only for debug/stats - * - * @return Array of 5 integers (sum equal numbers of rows) counting each filter use - */ - public int[] getFilterUseStat() { - return filterUseStat; - } + @Override + public void close() { + super.close(); + rowUnfiltered = null;// not really necessary... + rowUnfilteredPrev = null; + } + /** + * Only for debug/stats + * + * @return Array of 5 integers (sum equal numbers of rows) counting each + * filter use + */ + public int[] getFilterUseStat() { + return filterUseStat; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/ImageInfo.java b/teavm/src/main/java/ar/com/hjg/pngj/ImageInfo.java index 80758c8a..850ac2c0 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/ImageInfo.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/ImageInfo.java @@ -5,251 +5,261 @@ import java.util.zip.Checksum; /** * Simple immutable wrapper for basic image info. *

- * Some parameters are redundant, but the constructor receives an 'orthogonal' subset. + * Some parameters are redundant, but the constructor receives an 'orthogonal' + * subset. *

* ref: http://www.w3.org/TR/PNG/#11IHDR */ public class ImageInfo { - /** - * Absolute allowed maximum value for rows and cols (2^24 ~16 million). (bytesPerRow must fit in a 32bit integer, - * though total amount of pixels not necessarily). - */ - public static final int MAX_COLS_ROW = 16777216; + /** + * Absolute allowed maximum value for rows and cols (2^24 ~16 million). + * (bytesPerRow must fit in a 32bit integer, + * though total amount of pixels not necessarily). + */ + public static final int MAX_COLS_ROW = 16777216; - /** - * Cols= Image width, in pixels. - */ - public final int cols; + /** + * Cols= Image width, in pixels. + */ + public final int cols; - /** - * Rows= Image height, in pixels - */ - public final int rows; + /** + * Rows= Image height, in pixels + */ + public final int rows; - /** - * Bits per sample (per channel) in the buffer (1-2-4-8-16). This is 8-16 for RGB/ARGB images, 1-2-4-8 for grayscale. - * For indexed images, number of bits per palette index (1-2-4-8) - */ - public final int bitDepth; + /** + * Bits per sample (per channel) in the buffer (1-2-4-8-16). This is 8-16 + * for RGB/ARGB images, 1-2-4-8 for grayscale. + * For indexed images, number of bits per palette index (1-2-4-8) + */ + public final int bitDepth; - /** - * Number of channels, as used internally: 3 for RGB, 4 for RGBA, 2 for GA (gray with alpha), 1 for grayscale or - * indexed. - */ - public final int channels; + /** + * Number of channels, as used internally: 3 for RGB, 4 for RGBA, 2 for GA + * (gray with alpha), 1 for grayscale or + * indexed. + */ + public final int channels; - /** - * Flag: true if has alpha channel (RGBA/GA) - */ - public final boolean alpha; + /** + * Flag: true if has alpha channel (RGBA/GA) + */ + public final boolean alpha; - /** - * Flag: true if is grayscale (G/GA) - */ - public final boolean greyscale; + /** + * Flag: true if is grayscale (G/GA) + */ + public final boolean greyscale; - /** - * Flag: true if image is indexed, i.e., it has a palette - */ - public final boolean indexed; + /** + * Flag: true if image is indexed, i.e., it has a palette + */ + public final boolean indexed; - /** - * Flag: true if image internally uses less than one byte per sample (bit depth 1-2-4) - */ - public final boolean packed; + /** + * Flag: true if image internally uses less than one byte per sample (bit + * depth 1-2-4) + */ + public final boolean packed; - /** - * Bits used for each pixel in the buffer: channel * bitDepth - */ - public final int bitspPixel; + /** + * Bits used for each pixel in the buffer: channel * bitDepth + */ + public final int bitspPixel; - /** - * rounded up value: this is only used internally for filter - */ - public final int bytesPixel; + /** + * rounded up value: this is only used internally for filter + */ + public final int bytesPixel; - /** - * ceil(bitspp*cols/8) - does not include filter - */ - public final int bytesPerRow; + /** + * ceil(bitspp*cols/8) - does not include filter + */ + public final int bytesPerRow; - /** - * Equals cols * channels - */ - public final int samplesPerRow; + /** + * Equals cols * channels + */ + public final int samplesPerRow; - /** - * Amount of "packed samples" : when several samples are stored in a single byte (bitdepth 1,2 4) they are counted as - * one "packed sample". This is less that samplesPerRow only when bitdepth is 1-2-4 (flag packed = true) - *

- * This equals the number of elements in the scanline array if working with packedMode=true - *

- * For internal use, client code should rarely access this. - */ - public final int samplesPerRowPacked; + /** + * Amount of "packed samples" : when several samples are stored in a single + * byte (bitdepth 1,2 4) they are counted as + * one "packed sample". This is less that samplesPerRow only when bitdepth + * is 1-2-4 (flag packed = true) + *

+ * This equals the number of elements in the scanline array if working with + * packedMode=true + *

+ * For internal use, client code should rarely access this. + */ + public final int samplesPerRowPacked; - private long totalPixels = -1; // lazy getter + private long totalPixels = -1; // lazy getter - private long totalRawBytes = -1; // lazy getter + private long totalRawBytes = -1; // lazy getter - /** - * Short constructor: assumes truecolor (RGB/RGBA) - */ - public ImageInfo(int cols, int rows, int bitdepth, boolean alpha) { - this(cols, rows, bitdepth, alpha, false, false); - } + /** + * Short constructor: assumes truecolor (RGB/RGBA) + */ + public ImageInfo(final int cols, final int rows, final int bitdepth, final boolean alpha) { + this(cols, rows, bitdepth, alpha, false, false); + } - /** - * Full constructor - * - * @param cols Width in pixels - * @param rows Height in pixels - * @param bitdepth Bits per sample, in the buffer : 8-16 for RGB true color and greyscale - * @param alpha Flag: has an alpha channel (RGBA or GA) - * @param grayscale Flag: is gray scale (any bitdepth, with or without alpha) - * @param indexed Flag: has palette - */ - public ImageInfo(int cols, int rows, int bitdepth, boolean alpha, boolean grayscale, - boolean indexed) { - this.cols = cols; - this.rows = rows; - this.alpha = alpha; - this.indexed = indexed; - this.greyscale = grayscale; - if (greyscale && indexed) - throw new PngjException("palette and greyscale are mutually exclusive"); - this.channels = (grayscale || indexed) ? (alpha ? 2 : 1) : (alpha ? 4 : 3); - // http://www.w3.org/TR/PNG/#11IHDR - this.bitDepth = bitdepth; - this.packed = bitdepth < 8; - this.bitspPixel = (channels * this.bitDepth); - this.bytesPixel = (bitspPixel + 7) / 8; - this.bytesPerRow = (bitspPixel * cols + 7) / 8; - this.samplesPerRow = channels * this.cols; - this.samplesPerRowPacked = packed ? bytesPerRow : samplesPerRow; - // several checks - switch (this.bitDepth) { - case 1: - case 2: - case 4: - if (!(this.indexed || this.greyscale)) - throw new PngjException("only indexed or grayscale can have bitdepth=" + this.bitDepth); - break; - case 8: - break; - case 16: - if (this.indexed) - throw new PngjException("indexed can't have bitdepth=" + this.bitDepth); - break; - default: - throw new PngjException("invalid bitdepth=" + this.bitDepth); - } - if (cols < 1 || cols > MAX_COLS_ROW) - throw new PngjException("invalid cols=" + cols + " ???"); - if (rows < 1 || rows > MAX_COLS_ROW) - throw new PngjException("invalid rows=" + rows + " ???"); - if (samplesPerRow < 1) - throw new PngjException("invalid image parameters (overflow?)"); - } + /** + * Full constructor + * + * @param cols + * Width in pixels + * @param rows + * Height in pixels + * @param bitdepth + * Bits per sample, in the buffer : 8-16 for RGB true color and + * greyscale + * @param alpha + * Flag: has an alpha channel (RGBA or GA) + * @param grayscale + * Flag: is gray scale (any bitdepth, with or without alpha) + * @param indexed + * Flag: has palette + */ + public ImageInfo(final int cols, final int rows, final int bitdepth, final boolean alpha, final boolean grayscale, final boolean indexed) { + this.cols = cols; + this.rows = rows; + this.alpha = alpha; + this.indexed = indexed; + greyscale = grayscale; + if (greyscale && indexed) + throw new PngjException("palette and greyscale are mutually exclusive"); + channels = grayscale || indexed ? alpha ? 2 : 1 : alpha ? 4 : 3; + // http://www.w3.org/TR/PNG/#11IHDR + bitDepth = bitdepth; + packed = bitdepth < 8; + bitspPixel = channels * bitDepth; + bytesPixel = (bitspPixel + 7) / 8; + bytesPerRow = (bitspPixel * cols + 7) / 8; + samplesPerRow = channels * this.cols; + samplesPerRowPacked = packed ? bytesPerRow : samplesPerRow; + // several checks + switch (bitDepth) { + case 1: + case 2: + case 4: + if (!(this.indexed || greyscale)) + throw new PngjException("only indexed or grayscale can have bitdepth=" + bitDepth); + break; + case 8: + break; + case 16: + if (this.indexed) + throw new PngjException("indexed can't have bitdepth=" + bitDepth); + break; + default: + throw new PngjException("invalid bitdepth=" + bitDepth); + } + if (cols < 1 || cols > ImageInfo.MAX_COLS_ROW) + throw new PngjException("invalid cols=" + cols + " ???"); + if (rows < 1 || rows > ImageInfo.MAX_COLS_ROW) + throw new PngjException("invalid rows=" + rows + " ???"); + if (samplesPerRow < 1) + throw new PngjException("invalid image parameters (overflow?)"); + } - /** - * returns a copy with different size - * - * @param cols if non-positive, the original is used - * @param rows if non-positive, the original is used - * @return a new copy with the specified size and same properties - */ - public ImageInfo withSize(int cols, int rows) { - return new ImageInfo(cols > 0 ? cols : this.cols, rows > 0 ? rows : this.rows, this.bitDepth, - this.alpha, this.greyscale, this.indexed); - } + /** + * returns a copy with different size + * + * @param cols + * if non-positive, the original is used + * @param rows + * if non-positive, the original is used + * @return a new copy with the specified size and same properties + */ + public ImageInfo withSize(final int cols, final int rows) { + return new ImageInfo(cols > 0 ? cols : this.cols, rows > 0 ? rows : this.rows, bitDepth, alpha, greyscale, indexed); + } - public long getTotalPixels() { - if (totalPixels < 0) - totalPixels = cols * (long) rows; - return totalPixels; - } + public long getTotalPixels() { + if (totalPixels < 0) + totalPixels = cols * (long) rows; + return totalPixels; + } - /** - * Total uncompressed bytes in IDAT, including filter byte. This is not valid for interlaced. - */ - public long getTotalRawBytes() { - if (totalRawBytes < 0) - totalRawBytes = (bytesPerRow + 1) * (long) rows; - return totalRawBytes; - } + /** + * Total uncompressed bytes in IDAT, including filter byte. This is not + * valid for interlaced. + */ + public long getTotalRawBytes() { + if (totalRawBytes < 0) + totalRawBytes = (bytesPerRow + 1) * (long) rows; + return totalRawBytes; + } - @Override - public String toString() { - return "ImageInfo [cols=" + cols + ", rows=" + rows + ", bitDepth=" + bitDepth + ", channels=" - + channels + ", alpha=" + alpha + ", greyscale=" + greyscale + ", indexed=" + indexed + "]"; - } + @Override + public String toString() { + return "ImageInfo [cols=" + cols + ", rows=" + rows + ", bitDepth=" + bitDepth + ", channels=" + channels + ", alpha=" + alpha + ", greyscale=" + greyscale + ", indexed=" + indexed + "]"; + } - /** - * Brief info: COLSxROWS[dBITDEPTH][a][p][g] ( the default dBITDEPTH='d8' is ommited) - **/ - public String toStringBrief() { - return String.valueOf(cols) + "x" + rows + (bitDepth != 8 ? ("d" + bitDepth) : "") - + (alpha ? "a" : "") + (indexed ? "p" : "") + (greyscale ? "g" : ""); - } + /** + * Brief info: COLSxROWS[dBITDEPTH][a][p][g] ( the default dBITDEPTH='d8' is + * ommited) + **/ + public String toStringBrief() { + return String.valueOf(cols) + "x" + rows + (bitDepth != 8 ? "d" + bitDepth : "") + (alpha ? "a" : "") + (indexed ? "p" : "") + (greyscale ? "g" : ""); + } - public String toStringDetail() { - return "ImageInfo [cols=" + cols + ", rows=" + rows + ", bitDepth=" + bitDepth + ", channels=" - + channels + ", bitspPixel=" + bitspPixel + ", bytesPixel=" + bytesPixel + ", bytesPerRow=" - + bytesPerRow + ", samplesPerRow=" + samplesPerRow + ", samplesPerRowP=" - + samplesPerRowPacked + ", alpha=" + alpha + ", greyscale=" + greyscale + ", indexed=" - + indexed + ", packed=" + packed + "]"; - } + public String toStringDetail() { + return "ImageInfo [cols=" + cols + ", rows=" + rows + ", bitDepth=" + bitDepth + ", channels=" + channels + ", bitspPixel=" + bitspPixel + ", bytesPixel=" + bytesPixel + ", bytesPerRow=" + bytesPerRow + ", samplesPerRow=" + samplesPerRow + ", samplesPerRowP=" + samplesPerRowPacked + ", alpha=" + alpha + ", greyscale=" + greyscale + ", indexed=" + indexed + ", packed=" + packed + "]"; + } + void updateCrc(final Checksum crc) { + crc.update((byte) rows); + crc.update((byte) (rows >> 8)); + crc.update((byte) (rows >> 16)); + crc.update((byte) cols); + crc.update((byte) (cols >> 8)); + crc.update((byte) (cols >> 16)); + crc.update((byte) bitDepth); + crc.update((byte) (indexed ? 1 : 2)); + crc.update((byte) (greyscale ? 3 : 4)); + crc.update((byte) (alpha ? 3 : 4)); + } - void updateCrc(Checksum crc) { - crc.update((byte) rows); - crc.update((byte) (rows >> 8)); - crc.update((byte) (rows >> 16)); - crc.update((byte) cols); - crc.update((byte) (cols >> 8)); - crc.update((byte) (cols >> 16)); - crc.update((byte) (bitDepth)); - crc.update((byte) (indexed ? 1 : 2)); - crc.update((byte) (greyscale ? 3 : 4)); - crc.update((byte) (alpha ? 3 : 4)); - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (alpha ? 1231 : 1237); + result = prime * result + bitDepth; + result = prime * result + cols; + result = prime * result + (greyscale ? 1231 : 1237); + result = prime * result + (indexed ? 1231 : 1237); + result = prime * result + rows; + return result; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (alpha ? 1231 : 1237); - result = prime * result + bitDepth; - result = prime * result + cols; - result = prime * result + (greyscale ? 1231 : 1237); - result = prime * result + (indexed ? 1231 : 1237); - result = prime * result + rows; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ImageInfo other = (ImageInfo) obj; - if (alpha != other.alpha) - return false; - if (bitDepth != other.bitDepth) - return false; - if (cols != other.cols) - return false; - if (greyscale != other.greyscale) - return false; - if (indexed != other.indexed) - return false; - if (rows != other.rows) - return false; - return true; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final ImageInfo other = (ImageInfo) obj; + if (alpha != other.alpha) + return false; + if (bitDepth != other.bitDepth) + return false; + if (cols != other.cols) + return false; + if (greyscale != other.greyscale) + return false; + if (indexed != other.indexed) + return false; + if (rows != other.rows) + return false; + return true; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/ImageLineByte.java b/teavm/src/main/java/ar/com/hjg/pngj/ImageLineByte.java index 3c1146ca..f883e9d2 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/ImageLineByte.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/ImageLineByte.java @@ -3,184 +3,189 @@ package ar.com.hjg.pngj; /** * Lightweight wrapper for an image scanline, used for read and write. *

- * This object can be (usually it is) reused while iterating over the image lines. + * This object can be (usually it is) reused while iterating over the image + * lines. *

* See scanline field, to understand the format. - * - * Format: byte (one bytes per sample) (for 16bpp the extra byte is placed in an extra array) + * + * Format: byte (one bytes per sample) (for 16bpp the extra byte is placed in an + * extra array) */ public class ImageLineByte implements IImageLine, IImageLineArray { - public final ImageInfo imgInfo; + public final ImageInfo imgInfo; - final byte[] scanline; - final byte[] scanline2; // only used for 16 bpp (less significant byte) Normally you'd prefer - // ImageLineInt in this case + final byte[] scanline; + final byte[] scanline2; // only used for 16 bpp (less significant byte) Normally you'd prefer + // ImageLineInt in this case - protected FilterType filterType; // informational ; only filled by the reader. not significant for - // interlaced - final int size; // = imgInfo.samplePerRowPacked, if packed:imgInfo.samplePerRow elswhere + protected FilterType filterType; // informational ; only filled by the reader. not significant for + // interlaced + final int size; // = imgInfo.samplePerRowPacked, if packed:imgInfo.samplePerRow elswhere - public ImageLineByte(ImageInfo imgInfo) { - this(imgInfo, null); - } + public ImageLineByte(final ImageInfo imgInfo) { + this(imgInfo, null); + } - public ImageLineByte(ImageInfo imgInfo, byte[] sci) { - this.imgInfo = imgInfo; - filterType = FilterType.FILTER_UNKNOWN; - size = imgInfo.samplesPerRow; - scanline = sci != null && sci.length >= size ? sci : new byte[size]; - scanline2 = imgInfo.bitDepth == 16 ? new byte[size] : null; - } + public ImageLineByte(final ImageInfo imgInfo, final byte[] sci) { + this.imgInfo = imgInfo; + filterType = FilterType.FILTER_UNKNOWN; + size = imgInfo.samplesPerRow; + scanline = sci != null && sci.length >= size ? sci : new byte[size]; + scanline2 = imgInfo.bitDepth == 16 ? new byte[size] : null; + } - /** - * Returns a factory for this object - */ - public static IImageLineFactory getFactory() { - return new IImageLineFactory() { - public ImageLineByte createImageLine(ImageInfo iminfo) { - return new ImageLineByte(iminfo); - } - }; - } + /** + * Returns a factory for this object + */ + public static IImageLineFactory getFactory() { + return iminfo -> new ImageLineByte(iminfo); + } - public FilterType getFilterUsed() { - return filterType; - } + public FilterType getFilterUsed() { + return filterType; + } - /** - * One byte per sample. This can be used also for 16bpp images, but in this case this loses the less significant - * 8-bits ; see also getScanlineByte2 and getElem. - */ - public byte[] getScanlineByte() { - return scanline; - } + /** + * One byte per sample. This can be used also for 16bpp images, but in this + * case this loses the less significant + * 8-bits ; see also getScanlineByte2 and getElem. + */ + public byte[] getScanlineByte() { + return scanline; + } - /** - * only for 16bpp (less significant byte) - * - * @return null for less than 16bpp - */ - public byte[] getScanlineByte2() { - return scanline2; - } + /** + * only for 16bpp (less significant byte) + * + * @return null for less than 16bpp + */ + public byte[] getScanlineByte2() { + return scanline2; + } - /** - * Basic info - */ - public String toString() { - return " cols=" + imgInfo.cols + " bpc=" + imgInfo.bitDepth + " size=" + scanline.length; - } + /** + * Basic info + */ + @Override + public String toString() { + return " cols=" + imgInfo.cols + " bpc=" + imgInfo.bitDepth + " size=" + scanline.length; + } - public void readFromPngRaw(byte[] raw, final int len, final int offset, final int step) { - filterType = FilterType.getByVal(raw[0]); // only for non interlaced line the filter is significative - int len1 = len - 1; - int step1 = (step - 1) * imgInfo.channels; - if (imgInfo.bitDepth == 8) { - if (step == 1) {// 8bispp non-interlaced: most important case, should be optimized - System.arraycopy(raw, 1, scanline, 0, len1); - } else {// 8bispp interlaced - for (int s = 1, c = 0, i = offset * imgInfo.channels; s <= len1; s++, i++) { - scanline[i] = raw[s]; - c++; - if (c == imgInfo.channels) { - c = 0; - i += step1; - } - } - } - } else if (imgInfo.bitDepth == 16) { - if (step == 1) {// 16bispp non-interlaced - for (int i = 0, s = 1; i < imgInfo.samplesPerRow; i++) { - scanline[i] = raw[s++]; // get the first byte - scanline2[i] = raw[s++]; // get the first byte - } - } else { - for (int s = 1, c = 0, i = offset != 0 ? offset * imgInfo.channels : 0; s <= len1; i++) { - scanline[i] = raw[s++]; - scanline2[i] = raw[s++]; - c++; - if (c == imgInfo.channels) { - c = 0; - i += step1; - } - } - } - } else { // packed formats - int mask0, mask, shi, bd; - bd = imgInfo.bitDepth; - mask0 = ImageLineHelper.getMaskForPackedFormats(bd); - for (int i = offset * imgInfo.channels, r = 1, c = 0; r < len; r++) { - mask = mask0; - shi = 8 - bd; - do { - scanline[i] = (byte) ((raw[r] & mask) >> shi); - mask >>= bd; - shi -= bd; - i++; - c++; - if (c == imgInfo.channels) { - c = 0; - i += step1; - } - } while (mask != 0 && i < size); - } - } - } + @Override + public void readFromPngRaw(final byte[] raw, final int len, final int offset, final int step) { + filterType = FilterType.getByVal(raw[0]); // only for non interlaced line the filter is significative + final int len1 = len - 1; + final int step1 = (step - 1) * imgInfo.channels; + if (imgInfo.bitDepth == 8) { + if (step == 1) + System.arraycopy(raw, 1, scanline, 0, len1); + else + for (int s = 1, c = 0, i = offset * imgInfo.channels; s <= len1; s++, i++) { + scanline[i] = raw[s]; + c++; + if (c == imgInfo.channels) { + c = 0; + i += step1; + } + } + } else if (imgInfo.bitDepth == 16) { + if (step == 1) + for (int i = 0, s = 1; i < imgInfo.samplesPerRow; i++) { + scanline[i] = raw[s++]; // get the first byte + scanline2[i] = raw[s++]; // get the first byte + } + else + for (int s = 1, c = 0, i = offset != 0 ? offset * imgInfo.channels : 0; s <= len1; i++) { + scanline[i] = raw[s++]; + scanline2[i] = raw[s++]; + c++; + if (c == imgInfo.channels) { + c = 0; + i += step1; + } + } + } else { // packed formats + int mask0, mask, shi, bd; + bd = imgInfo.bitDepth; + mask0 = ImageLineHelper.getMaskForPackedFormats(bd); + for (int i = offset * imgInfo.channels, r = 1, c = 0; r < len; r++) { + mask = mask0; + shi = 8 - bd; + do { + scanline[i] = (byte) ((raw[r] & mask) >> shi); + mask >>= bd; + shi -= bd; + i++; + c++; + if (c == imgInfo.channels) { + c = 0; + i += step1; + } + } while (mask != 0 && i < size); + } + } + } - public void writeToPngRaw(byte[] raw) { - raw[0] = (byte) filterType.val; - if (imgInfo.bitDepth == 8) { - System.arraycopy(scanline, 0, raw, 1, size); - } else if (imgInfo.bitDepth == 16) { - for (int i = 0, s = 1; i < size; i++) { - raw[s++] = scanline[i]; - raw[s++] = scanline2[i]; - } - } else { // packed formats - int shi, bd, v; - bd = imgInfo.bitDepth; - shi = 8 - bd; - v = 0; - for (int i = 0, r = 1; i < size; i++) { - v |= (scanline[i] << shi); - shi -= bd; - if (shi < 0 || i == size - 1) { - raw[r++] = (byte) v; - shi = 8 - bd; - v = 0; - } - } - } - } + @Override + public void writeToPngRaw(final byte[] raw) { + raw[0] = (byte) filterType.val; + if (imgInfo.bitDepth == 8) + System.arraycopy(scanline, 0, raw, 1, size); + else if (imgInfo.bitDepth == 16) + for (int i = 0, s = 1; i < size; i++) { + raw[s++] = scanline[i]; + raw[s++] = scanline2[i]; + } + else { // packed formats + int shi, bd, v; + bd = imgInfo.bitDepth; + shi = 8 - bd; + v = 0; + for (int i = 0, r = 1; i < size; i++) { + v |= scanline[i] << shi; + shi -= bd; + if (shi < 0 || i == size - 1) { + raw[r++] = (byte) v; + shi = 8 - bd; + v = 0; + } + } + } + } - public void endReadFromPngRaw() {} + @Override + public void endReadFromPngRaw() {} - public int getSize() { - return size; - } + @Override + public int getSize() { + return size; + } - public int getElem(int i) { - return scanline2 == null ? scanline[i] & 0xFF : ((scanline[i] & 0xFF) << 8) - | (scanline2[i] & 0xFF); - } + @Override + public int getElem(final int i) { + return scanline2 == null ? scanline[i] & 0xFF : (scanline[i] & 0xFF) << 8 | scanline2[i] & 0xFF; + } - public byte[] getScanline() { - return scanline; - } + public byte[] getScanline() { + return scanline; + } - public ImageInfo getImageInfo() { - return imgInfo; - } + @Override + public ImageInfo getImageInfo() { + return imgInfo; + } - public FilterType getFilterType() { - return filterType; - } + @Override + public FilterType getFilterType() { + return filterType; + } - /** - * This should rarely be used by client code. Only relevant if FilterPreserve==true - */ - public void setFilterType(FilterType ft) { - filterType = ft; - } + /** + * This should rarely be used by client code. Only relevant if + * FilterPreserve==true + */ + public void setFilterType(final FilterType ft) { + filterType = ft; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/ImageLineHelper.java b/teavm/src/main/java/ar/com/hjg/pngj/ImageLineHelper.java index ee22d7e0..6deb44bc 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/ImageLineHelper.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/ImageLineHelper.java @@ -8,463 +8,462 @@ import ar.com.hjg.pngj.chunks.PngChunkTRNS; /** * Bunch of utility static methods to proces an image line at the pixel level. *

- * WARNING: this has little testing/optimizing, and this API is not stable. some methods will probably be changed or + * WARNING: this has little testing/optimizing, and this API is not stable. some + * methods will probably be changed or * removed if future releases. *

- * WARNING: most methods for getting/setting values work currently only for ImageLine or ImageLineByte + * WARNING: most methods for getting/setting values work currently only for + * ImageLine or ImageLineByte */ public class ImageLineHelper { - static int[] DEPTH_UNPACK_1; - static int[] DEPTH_UNPACK_2; - static int[] DEPTH_UNPACK_4; - static int[][] DEPTH_UNPACK; + static int[] DEPTH_UNPACK_1; + static int[] DEPTH_UNPACK_2; + static int[] DEPTH_UNPACK_4; + static int[][] DEPTH_UNPACK; - static { - initDepthScale(); - } + static { + ImageLineHelper.initDepthScale(); + } - private static void initDepthScale() { - DEPTH_UNPACK_1 = new int[2]; - for (int i = 0; i < 2; i++) - DEPTH_UNPACK_1[i] = i * 255; - DEPTH_UNPACK_2 = new int[4]; - for (int i = 0; i < 4; i++) - DEPTH_UNPACK_2[i] = (i * 255) / 3; - DEPTH_UNPACK_4 = new int[16]; - for (int i = 0; i < 16; i++) - DEPTH_UNPACK_4[i] = (i * 255) / 15; - DEPTH_UNPACK = new int[][] {null, DEPTH_UNPACK_1, DEPTH_UNPACK_2, null, DEPTH_UNPACK_4}; - } + private static void initDepthScale() { + ImageLineHelper.DEPTH_UNPACK_1 = new int[2]; + for (int i = 0; i < 2; i++) + ImageLineHelper.DEPTH_UNPACK_1[i] = i * 255; + ImageLineHelper.DEPTH_UNPACK_2 = new int[4]; + for (int i = 0; i < 4; i++) + ImageLineHelper.DEPTH_UNPACK_2[i] = i * 255 / 3; + ImageLineHelper.DEPTH_UNPACK_4 = new int[16]; + for (int i = 0; i < 16; i++) + ImageLineHelper.DEPTH_UNPACK_4[i] = i * 255 / 15; + ImageLineHelper.DEPTH_UNPACK = new int[][] { null, ImageLineHelper.DEPTH_UNPACK_1, ImageLineHelper.DEPTH_UNPACK_2, null, ImageLineHelper.DEPTH_UNPACK_4 }; + } - /** - * When the bitdepth is less than 8, the imageLine is usually returned/expected unscaled. This method upscales it in - * place. Eg, if bitdepth=1, values 0-1 will be converted to 0-255 - */ - public static void scaleUp(IImageLineArray line) { - if (line.getImageInfo().indexed || line.getImageInfo().bitDepth >= 8) - return; - final int[] scaleArray = DEPTH_UNPACK[line.getImageInfo().bitDepth]; - if (line instanceof ImageLineInt) { - ImageLineInt iline = (ImageLineInt) line; - for (int i = 0; i < iline.getSize(); i++) - iline.scanline[i] = scaleArray[iline.scanline[i]]; - } else if (line instanceof ImageLineByte) { - ImageLineByte iline = (ImageLineByte) line; - for (int i = 0; i < iline.getSize(); i++) - iline.scanline[i] = (byte) scaleArray[iline.scanline[i]]; - } else - throw new PngjException("not implemented"); - } + /** + * When the bitdepth is less than 8, the imageLine is usually + * returned/expected unscaled. This method upscales it in + * place. Eg, if bitdepth=1, values 0-1 will be converted to 0-255 + */ + public static void scaleUp(final IImageLineArray line) { + if (line.getImageInfo().indexed || line.getImageInfo().bitDepth >= 8) + return; + final int[] scaleArray = ImageLineHelper.DEPTH_UNPACK[line.getImageInfo().bitDepth]; + if (line instanceof ImageLineInt) { + final ImageLineInt iline = (ImageLineInt) line; + for (int i = 0; i < iline.getSize(); i++) + iline.scanline[i] = scaleArray[iline.scanline[i]]; + } else if (line instanceof ImageLineByte) { + final ImageLineByte iline = (ImageLineByte) line; + for (int i = 0; i < iline.getSize(); i++) + iline.scanline[i] = (byte) scaleArray[iline.scanline[i]]; + } else + throw new PngjException("not implemented"); + } - /** - * Reverse of {@link #scaleUp(IImageLineArray)} - */ - public static void scaleDown(IImageLineArray line) { - if (line.getImageInfo().indexed || line.getImageInfo().bitDepth >= 8) - return; - if (line instanceof ImageLineInt) { - final int scalefactor = 8 - line.getImageInfo().bitDepth; - if (line instanceof ImageLineInt) { - ImageLineInt iline = (ImageLineInt) line; - for (int i = 0; i < line.getSize(); i++) - iline.scanline[i] = iline.scanline[i] >> scalefactor; - } else if (line instanceof ImageLineByte) { - ImageLineByte iline = (ImageLineByte) line; - for (int i = 0; i < line.getSize(); i++) - iline.scanline[i] = (byte) ((iline.scanline[i] & 0xFF) >> scalefactor); - } - } else - throw new PngjException("not implemented"); - } + /** + * Reverse of {@link #scaleUp(IImageLineArray)} + */ + public static void scaleDown(final IImageLineArray line) { + if (line.getImageInfo().indexed || line.getImageInfo().bitDepth >= 8) + return; + if (line instanceof ImageLineInt) { + final int scalefactor = 8 - line.getImageInfo().bitDepth; + if (line instanceof ImageLineInt) { + final ImageLineInt iline = (ImageLineInt) line; + for (int i = 0; i < line.getSize(); i++) + iline.scanline[i] = iline.scanline[i] >> scalefactor; + } else if (line instanceof ImageLineByte) { + final ImageLineByte iline = (ImageLineByte) line; + for (int i = 0; i < line.getSize(); i++) + iline.scanline[i] = (byte) ((iline.scanline[i] & 0xFF) >> scalefactor); + } + } else + throw new PngjException("not implemented"); + } - public static byte scaleUp(int bitdepth, byte v) { - return bitdepth < 8 ? (byte) DEPTH_UNPACK[bitdepth][v] : v; - } + public static byte scaleUp(final int bitdepth, final byte v) { + return bitdepth < 8 ? (byte) ImageLineHelper.DEPTH_UNPACK[bitdepth][v] : v; + } - public static byte scaleDown(int bitdepth, byte v) { - return bitdepth < 8 ? (byte) (v >> (8 - bitdepth)) : v; - } + public static byte scaleDown(final int bitdepth, final byte v) { + return bitdepth < 8 ? (byte) (v >> 8 - bitdepth) : v; + } - /** - * Given an indexed line with a palette, unpacks as a RGB array, or RGBA if a non nul PngChunkTRNS chunk is passed - * - * @param line ImageLine as returned from PngReader - * @param pal Palette chunk - * @param trns Transparency chunk, can be null (absent) - * @param buf Preallocated array, optional - * @return R G B (A), one sample 0-255 per array element. Ready for pngw.writeRowInt() - */ - public static int[] palette2rgb(ImageLineInt line, PngChunkPLTE pal, PngChunkTRNS trns, int[] buf) { - return palette2rgb(line, pal, trns, buf, false); - } + /** + * Given an indexed line with a palette, unpacks as a RGB array, or RGBA if + * a non nul PngChunkTRNS chunk is passed + * + * @param line + * ImageLine as returned from PngReader + * @param pal + * Palette chunk + * @param trns + * Transparency chunk, can be null (absent) + * @param buf + * Preallocated array, optional + * @return R G B (A), one sample 0-255 per array element. Ready for + * pngw.writeRowInt() + */ + public static int[] palette2rgb(final ImageLineInt line, final PngChunkPLTE pal, final PngChunkTRNS trns, + final int[] buf) { + return ImageLineHelper.palette2rgb(line, pal, trns, buf, false); + } - /** - * Warning: the line should be upscaled, see {@link #scaleUp(IImageLineArray)} - */ - static int[] lineToARGB32(ImageLineByte line, PngChunkPLTE pal, PngChunkTRNS trns, int[] buf) { - boolean alphachannel = line.imgInfo.alpha; - int cols = line.getImageInfo().cols; - if (buf == null || buf.length < cols) - buf = new int[cols]; - int index, rgb, alpha, ga, g; - if (line.getImageInfo().indexed) {// palette - int nindexesWithAlpha = trns != null ? trns.getPalletteAlpha().length : 0; - for (int c = 0; c < cols; c++) { - index = line.scanline[c] & 0xFF; - rgb = pal.getEntry(index); - alpha = index < nindexesWithAlpha ? trns.getPalletteAlpha()[index] : 255; - buf[c] = (alpha << 24) | rgb; - } - } else if (line.imgInfo.greyscale) { // gray - ga = trns != null ? trns.getGray() : -1; - for (int c = 0, c2 = 0; c < cols; c++) { - g = (line.scanline[c2++] & 0xFF); - alpha = alphachannel ? line.scanline[c2++] & 0xFF : (g != ga ? 255 : 0); - buf[c] = (alpha << 24) | g | (g << 8) | (g << 16); - } - } else { // true color - ga = trns != null ? trns.getRGB888() : -1; - for (int c = 0, c2 = 0; c < cols; c++) { - rgb = - ((line.scanline[c2++] & 0xFF) << 16) | ((line.scanline[c2++] & 0xFF) << 8) - | (line.scanline[c2++] & 0xFF); - alpha = alphachannel ? line.scanline[c2++] & 0xFF : (rgb != ga ? 255 : 0); - buf[c] = (alpha << 24) | rgb; - } - } - return buf; - } + /** + * Warning: the line should be upscaled, see + * {@link #scaleUp(IImageLineArray)} + */ + static int[] lineToARGB32(final ImageLineByte line, final PngChunkPLTE pal, final PngChunkTRNS trns, int[] buf) { + final boolean alphachannel = line.imgInfo.alpha; + final int cols = line.getImageInfo().cols; + if (buf == null || buf.length < cols) + buf = new int[cols]; + int index, rgb, alpha, ga, g; + if (line.getImageInfo().indexed) {// palette + final int nindexesWithAlpha = trns != null ? trns.getPalletteAlpha().length : 0; + for (int c = 0; c < cols; c++) { + index = line.scanline[c] & 0xFF; + rgb = pal.getEntry(index); + alpha = index < nindexesWithAlpha ? trns.getPalletteAlpha()[index] : 255; + buf[c] = alpha << 24 | rgb; + } + } else if (line.imgInfo.greyscale) { // gray + ga = trns != null ? trns.getGray() : -1; + for (int c = 0, c2 = 0; c < cols; c++) { + g = line.scanline[c2++] & 0xFF; + alpha = alphachannel ? line.scanline[c2++] & 0xFF : g != ga ? 255 : 0; + buf[c] = alpha << 24 | g | g << 8 | g << 16; + } + } else { // true color + ga = trns != null ? trns.getRGB888() : -1; + for (int c = 0, c2 = 0; c < cols; c++) { + rgb = (line.scanline[c2++] & 0xFF) << 16 | (line.scanline[c2++] & 0xFF) << 8 | line.scanline[c2++] & 0xFF; + alpha = alphachannel ? line.scanline[c2++] & 0xFF : rgb != ga ? 255 : 0; + buf[c] = alpha << 24 | rgb; + } + } + return buf; + } - /** - * Warning: the line should be upscaled, see {@link #scaleUp(IImageLineArray)} - */ - static byte[] lineToRGBA8888(ImageLineByte line, PngChunkPLTE pal, PngChunkTRNS trns, byte[] buf) { - boolean alphachannel = line.imgInfo.alpha; - int cols = line.imgInfo.cols; - int bytes = cols * 4; - if (buf == null || buf.length < bytes) - buf = new byte[bytes]; - int index, rgb, ga; - byte val; - if (line.imgInfo.indexed) {// palette - int nindexesWithAlpha = trns != null ? trns.getPalletteAlpha().length : 0; - for (int c = 0, b = 0; c < cols; c++) { - index = line.scanline[c] & 0xFF; - rgb = pal.getEntry(index); - buf[b++] = (byte) ((rgb >> 16) & 0xFF); - buf[b++] = (byte) ((rgb >> 8) & 0xFF); - buf[b++] = (byte) (rgb & 0xFF); - buf[b++] = (byte) (index < nindexesWithAlpha ? trns.getPalletteAlpha()[index] : 255); - } - } else if (line.imgInfo.greyscale) { // - ga = trns != null ? trns.getGray() : -1; - for (int c = 0, b = 0; b < bytes;) { - val = line.scanline[c++]; - buf[b++] = val; - buf[b++] = val; - buf[b++] = val; - buf[b++] = - alphachannel ? line.scanline[c++] : ((int) (val & 0xFF) == ga) ? (byte) 0 : (byte) 255; - } - } else { // true color - if (alphachannel) // same format! - System.arraycopy(line.scanline, 0, buf, 0, bytes); - else { - for (int c = 0, b = 0; b < bytes;) { - buf[b++] = line.scanline[c++]; - buf[b++] = line.scanline[c++]; - buf[b++] = line.scanline[c++]; - buf[b++] = (byte) (255); // tentative (probable) - if (trns != null && buf[b - 3] == (byte) trns.getRGB()[0] - && buf[b - 2] == (byte) trns.getRGB()[1] && buf[b - 1] == (byte) trns.getRGB()[2]) // not - // very - // efficient, - // but - // not - // frecuent - buf[b - 1] = 0; - } - } - } - return buf; - } + /** + * Warning: the line should be upscaled, see + * {@link #scaleUp(IImageLineArray)} + */ + static byte[] lineToRGBA8888(final ImageLineByte line, final PngChunkPLTE pal, final PngChunkTRNS trns, + byte[] buf) { + final boolean alphachannel = line.imgInfo.alpha; + final int cols = line.imgInfo.cols; + final int bytes = cols * 4; + if (buf == null || buf.length < bytes) + buf = new byte[bytes]; + int index, rgb, ga; + byte val; + if (line.imgInfo.indexed) {// palette + final int nindexesWithAlpha = trns != null ? trns.getPalletteAlpha().length : 0; + for (int c = 0, b = 0; c < cols; c++) { + index = line.scanline[c] & 0xFF; + rgb = pal.getEntry(index); + buf[b++] = (byte) (rgb >> 16 & 0xFF); + buf[b++] = (byte) (rgb >> 8 & 0xFF); + buf[b++] = (byte) (rgb & 0xFF); + buf[b++] = (byte) (index < nindexesWithAlpha ? trns.getPalletteAlpha()[index] : 255); + } + } else if (line.imgInfo.greyscale) { // + ga = trns != null ? trns.getGray() : -1; + for (int c = 0, b = 0; b < bytes;) { + val = line.scanline[c++]; + buf[b++] = val; + buf[b++] = val; + buf[b++] = val; + buf[b++] = alphachannel ? line.scanline[c++] : (val & 0xFF) == ga ? (byte) 0 : (byte) 255; + } + } else if (alphachannel) // same format! + System.arraycopy(line.scanline, 0, buf, 0, bytes); + else + for (int c = 0, b = 0; b < bytes;) { + buf[b++] = line.scanline[c++]; + buf[b++] = line.scanline[c++]; + buf[b++] = line.scanline[c++]; + buf[b++] = (byte) 255; // tentative (probable) + if (trns != null && buf[b - 3] == (byte) trns.getRGB()[0] && buf[b - 2] == (byte) trns.getRGB()[1] && buf[b - 1] == (byte) trns.getRGB()[2]) // not + // very + // efficient, + // but + // not + // frecuent + buf[b - 1] = 0; + } + return buf; + } - static byte[] lineToRGB888(ImageLineByte line, PngChunkPLTE pal, byte[] buf) { - boolean alphachannel = line.imgInfo.alpha; - int cols = line.imgInfo.cols; - int bytes = cols * 3; - if (buf == null || buf.length < bytes) - buf = new byte[bytes]; - byte val; - int[] rgb = new int[3]; - if (line.imgInfo.indexed) {// palette - for (int c = 0, b = 0; c < cols; c++) { - pal.getEntryRgb(line.scanline[c] & 0xFF, rgb); - buf[b++] = (byte) rgb[0]; - buf[b++] = (byte) rgb[1]; - buf[b++] = (byte) rgb[2]; - } - } else if (line.imgInfo.greyscale) { // - for (int c = 0, b = 0; b < bytes;) { - val = line.scanline[c++]; - buf[b++] = val; - buf[b++] = val; - buf[b++] = val; - if (alphachannel) - c++; // skip alpha - } - } else { // true color - if (!alphachannel) // same format! - System.arraycopy(line.scanline, 0, buf, 0, bytes); - else { - for (int c = 0, b = 0; b < bytes;) { - buf[b++] = line.scanline[c++]; - buf[b++] = line.scanline[c++]; - buf[b++] = line.scanline[c++]; - c++;// skip alpha - } - } - } - return buf; - } + static byte[] lineToRGB888(final ImageLineByte line, final PngChunkPLTE pal, byte[] buf) { + final boolean alphachannel = line.imgInfo.alpha; + final int cols = line.imgInfo.cols; + final int bytes = cols * 3; + if (buf == null || buf.length < bytes) + buf = new byte[bytes]; + byte val; + final int[] rgb = new int[3]; + if (line.imgInfo.indexed) + for (int c = 0, b = 0; c < cols; c++) { + pal.getEntryRgb(line.scanline[c] & 0xFF, rgb); + buf[b++] = (byte) rgb[0]; + buf[b++] = (byte) rgb[1]; + buf[b++] = (byte) rgb[2]; + } + else if (line.imgInfo.greyscale) + for (int c = 0, b = 0; b < bytes;) { + val = line.scanline[c++]; + buf[b++] = val; + buf[b++] = val; + buf[b++] = val; + if (alphachannel) + c++; // skip alpha + } + else if (!alphachannel) // same format! + System.arraycopy(line.scanline, 0, buf, 0, bytes); + else + for (int c = 0, b = 0; b < bytes;) { + buf[b++] = line.scanline[c++]; + buf[b++] = line.scanline[c++]; + buf[b++] = line.scanline[c++]; + c++;// skip alpha + } + return buf; + } - /** - * Same as palette2rgbx , but returns rgba always, even if trns is null - * - * @param line ImageLine as returned from PngReader - * @param pal Palette chunk - * @param trns Transparency chunk, can be null (absent) - * @param buf Preallocated array, optional - * @return R G B (A), one sample 0-255 per array element. Ready for pngw.writeRowInt() - */ - public static int[] palette2rgba(ImageLineInt line, PngChunkPLTE pal, PngChunkTRNS trns, int[] buf) { - return palette2rgb(line, pal, trns, buf, true); - } + /** + * Same as palette2rgbx , but returns rgba always, even if trns is null + * + * @param line + * ImageLine as returned from PngReader + * @param pal + * Palette chunk + * @param trns + * Transparency chunk, can be null (absent) + * @param buf + * Preallocated array, optional + * @return R G B (A), one sample 0-255 per array element. Ready for + * pngw.writeRowInt() + */ + public static int[] palette2rgba(final ImageLineInt line, final PngChunkPLTE pal, final PngChunkTRNS trns, + final int[] buf) { + return ImageLineHelper.palette2rgb(line, pal, trns, buf, true); + } - public static int[] palette2rgb(ImageLineInt line, PngChunkPLTE pal, int[] buf) { - return palette2rgb(line, pal, null, buf, false); - } + public static int[] palette2rgb(final ImageLineInt line, final PngChunkPLTE pal, final int[] buf) { + return ImageLineHelper.palette2rgb(line, pal, null, buf, false); + } - /** this is not very efficient, only for tests and troubleshooting */ - public static int[] convert2rgba(IImageLineArray line, PngChunkPLTE pal, PngChunkTRNS trns, - int[] buf) { - ImageInfo imi = line.getImageInfo(); - int nsamples = imi.cols * 4; - if (buf == null || buf.length < nsamples) - buf = new int[nsamples]; - int maxval = imi.bitDepth == 16 ? (1 << 16) - 1 : 255; - Arrays.fill(buf, maxval); + /** this is not very efficient, only for tests and troubleshooting */ + public static int[] convert2rgba(final IImageLineArray line, final PngChunkPLTE pal, final PngChunkTRNS trns, + int[] buf) { + final ImageInfo imi = line.getImageInfo(); + final int nsamples = imi.cols * 4; + if (buf == null || buf.length < nsamples) + buf = new int[nsamples]; + final int maxval = imi.bitDepth == 16 ? (1 << 16) - 1 : 255; + Arrays.fill(buf, maxval); - if (imi.indexed) { - int tlen = trns != null ? trns.getPalletteAlpha().length : 0; - for (int s = 0; s < imi.cols; s++) { - int index = line.getElem(s); - pal.getEntryRgb(index, buf, s * 4); - if (index < tlen) { - buf[s * 4 + 3] = trns.getPalletteAlpha()[index]; - } - } - } else if (imi.greyscale) { - int[] unpack = null; - if (imi.bitDepth < 8) - unpack = ImageLineHelper.DEPTH_UNPACK[imi.bitDepth]; - for (int s = 0, i = 0, p = 0; p < imi.cols; p++) { - buf[s++] = unpack != null ? unpack[line.getElem(i++)] : line.getElem(i++); - buf[s] = buf[s - 1]; - s++; - buf[s] = buf[s - 1]; - s++; - if (imi.channels == 2) - buf[s++] = unpack != null ? unpack[line.getElem(i++)] : line.getElem(i++); - else - buf[s++] = maxval; - } - } else { - for (int s = 0, i = 0, p = 0; p < imi.cols; p++) { - buf[s++] = line.getElem(i++); - buf[s++] = line.getElem(i++); - buf[s++] = line.getElem(i++); - buf[s++] = imi.alpha ? line.getElem(i++) : maxval; - } - } - return buf; - } + if (imi.indexed) { + final int tlen = trns != null ? trns.getPalletteAlpha().length : 0; + for (int s = 0; s < imi.cols; s++) { + final int index = line.getElem(s); + pal.getEntryRgb(index, buf, s * 4); + if (index < tlen) + buf[s * 4 + 3] = trns.getPalletteAlpha()[index]; + } + } else if (imi.greyscale) { + int[] unpack = null; + if (imi.bitDepth < 8) + unpack = ImageLineHelper.DEPTH_UNPACK[imi.bitDepth]; + for (int s = 0, i = 0, p = 0; p < imi.cols; p++) { + buf[s++] = unpack != null ? unpack[line.getElem(i++)] : line.getElem(i++); + buf[s] = buf[s - 1]; + s++; + buf[s] = buf[s - 1]; + s++; + if (imi.channels == 2) + buf[s++] = unpack != null ? unpack[line.getElem(i++)] : line.getElem(i++); + else + buf[s++] = maxval; + } + } else + for (int s = 0, i = 0, p = 0; p < imi.cols; p++) { + buf[s++] = line.getElem(i++); + buf[s++] = line.getElem(i++); + buf[s++] = line.getElem(i++); + buf[s++] = imi.alpha ? line.getElem(i++) : maxval; + } + return buf; + } + private static int[] palette2rgb(final IImageLine line, final PngChunkPLTE pal, final PngChunkTRNS trns, int[] buf, + final boolean alphaForced) { + final boolean isalpha = trns != null; + final int channels = isalpha ? 4 : 3; + final ImageLineInt linei = (ImageLineInt) (line instanceof ImageLineInt ? line : null); + final ImageLineByte lineb = (ImageLineByte) (line instanceof ImageLineByte ? line : null); + final boolean isbyte = lineb != null; + final int cols = linei != null ? linei.imgInfo.cols : lineb.imgInfo.cols; + final int nsamples = cols * channels; + if (buf == null || buf.length < nsamples) + buf = new int[nsamples]; + final int nindexesWithAlpha = trns != null ? trns.getPalletteAlpha().length : 0; + for (int c = 0; c < cols; c++) { + final int index = isbyte ? lineb.scanline[c] & 0xFF : linei.scanline[c]; + pal.getEntryRgb(index, buf, c * channels); + if (isalpha) { + final int alpha = index < nindexesWithAlpha ? trns.getPalletteAlpha()[index] : 255; + buf[c * channels + 3] = alpha; + } + } + return buf; + } + /** + * what follows is pretty uninteresting/untested/obsolete, subject to change + */ + /** + * Just for basic info or debugging. Shows values for first and last pixel. + * Does not include alpha + */ + public static String infoFirstLastPixels(final ImageLineInt line) { + return line.imgInfo.channels == 1 ? String.format("first=(%d) last=(%d)", line.scanline[0], line.scanline[line.scanline.length - 1]) : String.format("first=(%d %d %d) last=(%d %d %d)", line.scanline[0], line.scanline[1], line.scanline[2], line.scanline[line.scanline.length - line.imgInfo.channels], line.scanline[line.scanline.length - line.imgInfo.channels + 1], line.scanline[line.scanline.length - line.imgInfo.channels + 2]); + } - private static int[] palette2rgb(IImageLine line, PngChunkPLTE pal, PngChunkTRNS trns, int[] buf, - boolean alphaForced) { - boolean isalpha = trns != null; - int channels = isalpha ? 4 : 3; - ImageLineInt linei = (ImageLineInt) (line instanceof ImageLineInt ? line : null); - ImageLineByte lineb = (ImageLineByte) (line instanceof ImageLineByte ? line : null); - boolean isbyte = lineb != null; - int cols = linei != null ? linei.imgInfo.cols : lineb.imgInfo.cols; - int nsamples = cols * channels; - if (buf == null || buf.length < nsamples) - buf = new int[nsamples]; - int nindexesWithAlpha = trns != null ? trns.getPalletteAlpha().length : 0; - for (int c = 0; c < cols; c++) { - int index = isbyte ? (lineb.scanline[c] & 0xFF) : linei.scanline[c]; - pal.getEntryRgb(index, buf, c * channels); - if (isalpha) { - int alpha = index < nindexesWithAlpha ? trns.getPalletteAlpha()[index] : 255; - buf[c * channels + 3] = alpha; - } - } - return buf; - } + /** + * integer packed R G B only for bitdepth=8! (does not check!) + * + **/ + public static int getPixelRGB8(final IImageLine line, final int column) { + if (line instanceof ImageLineInt) { + final int offset = column * ((ImageLineInt) line).imgInfo.channels; + final int[] scanline = ((ImageLineInt) line).getScanline(); + return scanline[offset] << 16 | scanline[offset + 1] << 8 | scanline[offset + 2]; + } else if (line instanceof ImageLineByte) { + final int offset = column * ((ImageLineByte) line).imgInfo.channels; + final byte[] scanline = ((ImageLineByte) line).getScanline(); + return (scanline[offset] & 0xff) << 16 | (scanline[offset + 1] & 0xff) << 8 | scanline[offset + 2] & 0xff; + } else + throw new PngjException("Not supported " + line.getClass()); + } - /** - * what follows is pretty uninteresting/untested/obsolete, subject to change - */ - /** - * Just for basic info or debugging. Shows values for first and last pixel. Does not include alpha - */ - public static String infoFirstLastPixels(ImageLineInt line) { - return line.imgInfo.channels == 1 ? String.format("first=(%d) last=(%d)", line.scanline[0], - line.scanline[line.scanline.length - 1]) : String.format( - "first=(%d %d %d) last=(%d %d %d)", line.scanline[0], line.scanline[1], line.scanline[2], - line.scanline[line.scanline.length - line.imgInfo.channels], - line.scanline[line.scanline.length - line.imgInfo.channels + 1], - line.scanline[line.scanline.length - line.imgInfo.channels + 2]); - } + public static int getPixelARGB8(final IImageLine line, final int column) { + if (line instanceof ImageLineInt) { + final int offset = column * ((ImageLineInt) line).imgInfo.channels; + final int[] scanline = ((ImageLineInt) line).getScanline(); + return scanline[offset + 3] << 24 | scanline[offset] << 16 | scanline[offset + 1] << 8 | scanline[offset + 2]; + } else if (line instanceof ImageLineByte) { + final int offset = column * ((ImageLineByte) line).imgInfo.channels; + final byte[] scanline = ((ImageLineByte) line).getScanline(); + return (scanline[offset + 3] & 0xff) << 24 | (scanline[offset] & 0xff) << 16 | (scanline[offset + 1] & 0xff) << 8 | scanline[offset + 2] & 0xff; + } else + throw new PngjException("Not supported " + line.getClass()); + } - /** - * integer packed R G B only for bitdepth=8! (does not check!) - * - **/ - public static int getPixelRGB8(IImageLine line, int column) { - if (line instanceof ImageLineInt) { - int offset = column * ((ImageLineInt) line).imgInfo.channels; - int[] scanline = ((ImageLineInt) line).getScanline(); - return (scanline[offset] << 16) | (scanline[offset + 1] << 8) | (scanline[offset + 2]); - } else if (line instanceof ImageLineByte) { - int offset = column * ((ImageLineByte) line).imgInfo.channels; - byte[] scanline = ((ImageLineByte) line).getScanline(); - return ((scanline[offset] & 0xff) << 16) | ((scanline[offset + 1] & 0xff) << 8) - | ((scanline[offset + 2] & 0xff)); - } else - throw new PngjException("Not supported " + line.getClass()); - } + public static void setPixelsRGB8(final ImageLineInt line, final int[] rgb) { + for (int i = 0, j = 0; i < line.imgInfo.cols; i++) { + line.scanline[j++] = rgb[i] >> 16 & 0xFF; + line.scanline[j++] = rgb[i] >> 8 & 0xFF; + line.scanline[j++] = rgb[i] & 0xFF; + } + } - public static int getPixelARGB8(IImageLine line, int column) { - if (line instanceof ImageLineInt) { - int offset = column * ((ImageLineInt) line).imgInfo.channels; - int[] scanline = ((ImageLineInt) line).getScanline(); - return (scanline[offset + 3] << 24) | (scanline[offset] << 16) | (scanline[offset + 1] << 8) - | (scanline[offset + 2]); - } else if (line instanceof ImageLineByte) { - int offset = column * ((ImageLineByte) line).imgInfo.channels; - byte[] scanline = ((ImageLineByte) line).getScanline(); - return (((scanline[offset + 3] & 0xff) << 24) | ((scanline[offset] & 0xff) << 16) - | ((scanline[offset + 1] & 0xff) << 8) | ((scanline[offset + 2] & 0xff))); - } else - throw new PngjException("Not supported " + line.getClass()); - } + public static void setPixelRGB8(final ImageLineInt line, int col, final int r, final int g, final int b) { + col *= line.imgInfo.channels; + line.scanline[col++] = r; + line.scanline[col++] = g; + line.scanline[col] = b; + } - public static void setPixelsRGB8(ImageLineInt line, int[] rgb) { - for (int i = 0, j = 0; i < line.imgInfo.cols; i++) { - line.scanline[j++] = ((rgb[i] >> 16) & 0xFF); - line.scanline[j++] = ((rgb[i] >> 8) & 0xFF); - line.scanline[j++] = ((rgb[i] & 0xFF)); - } - } + public static void setPixelRGB8(final ImageLineInt line, final int col, final int rgb) { + ImageLineHelper.setPixelRGB8(line, col, rgb >> 16 & 0xFF, rgb >> 8 & 0xFF, rgb & 0xFF); + } - public static void setPixelRGB8(ImageLineInt line, int col, int r, int g, int b) { - col *= line.imgInfo.channels; - line.scanline[col++] = r; - line.scanline[col++] = g; - line.scanline[col] = b; - } + public static void setPixelsRGBA8(final ImageLineInt line, final int[] rgb) { + for (int i = 0, j = 0; i < line.imgInfo.cols; i++) { + line.scanline[j++] = rgb[i] >> 16 & 0xFF; + line.scanline[j++] = rgb[i] >> 8 & 0xFF; + line.scanline[j++] = rgb[i] & 0xFF; + line.scanline[j++] = rgb[i] >> 24 & 0xFF; + } + } - public static void setPixelRGB8(ImageLineInt line, int col, int rgb) { - setPixelRGB8(line, col, (rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF); - } + public static void setPixelRGBA8(final ImageLineInt line, int col, final int r, final int g, final int b, + final int a) { + col *= line.imgInfo.channels; + line.scanline[col++] = r; + line.scanline[col++] = g; + line.scanline[col++] = b; + line.scanline[col] = a; + } - public static void setPixelsRGBA8(ImageLineInt line, int[] rgb) { - for (int i = 0, j = 0; i < line.imgInfo.cols; i++) { - line.scanline[j++] = ((rgb[i] >> 16) & 0xFF); - line.scanline[j++] = ((rgb[i] >> 8) & 0xFF); - line.scanline[j++] = ((rgb[i] & 0xFF)); - line.scanline[j++] = ((rgb[i] >> 24) & 0xFF); - } - } + public static void setPixelRGBA8(final ImageLineInt line, final int col, final int rgb) { + ImageLineHelper.setPixelRGBA8(line, col, rgb >> 16 & 0xFF, rgb >> 8 & 0xFF, rgb & 0xFF, rgb >> 24 & 0xFF); + } - public static void setPixelRGBA8(ImageLineInt line, int col, int r, int g, int b, int a) { - col *= line.imgInfo.channels; - line.scanline[col++] = r; - line.scanline[col++] = g; - line.scanline[col++] = b; - line.scanline[col] = a; - } + public static void setValD(final ImageLineInt line, final int i, final double d) { + line.scanline[i] = ImageLineHelper.double2int(line, d); + } - public static void setPixelRGBA8(ImageLineInt line, int col, int rgb) { - setPixelRGBA8(line, col, (rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF, (rgb >> 24) & 0xFF); - } + public static int interpol(final int a, final int b, final int c, final int d, final double dx, final double dy) { + // a b -> x (0-1) + // c d + final double e = a * (1.0 - dx) + b * dx; + final double f = c * (1.0 - dx) + d * dx; + return (int) (e * (1 - dy) + f * dy + 0.5); + } - public static void setValD(ImageLineInt line, int i, double d) { - line.scanline[i] = double2int(line, d); - } + public static double int2double(final ImageLineInt line, final int p) { + return line.imgInfo.bitDepth == 16 ? p / 65535.0 : p / 255.0; + // TODO: replace my multiplication? check for other bitdepths + } - public static int interpol(int a, int b, int c, int d, double dx, double dy) { - // a b -> x (0-1) - // c d - double e = a * (1.0 - dx) + b * dx; - double f = c * (1.0 - dx) + d * dx; - return (int) (e * (1 - dy) + f * dy + 0.5); - } + public static double int2doubleClamped(final ImageLineInt line, final int p) { + // TODO: replace my multiplication? + final double d = line.imgInfo.bitDepth == 16 ? p / 65535.0 : p / 255.0; + return d <= 0.0 ? 0 : d >= 1.0 ? 1.0 : d; + } - public static double int2double(ImageLineInt line, int p) { - return line.imgInfo.bitDepth == 16 ? p / 65535.0 : p / 255.0; - // TODO: replace my multiplication? check for other bitdepths - } + public static int double2int(final ImageLineInt line, double d) { + d = d <= 0.0 ? 0 : d >= 1.0 ? 1.0 : d; + return line.imgInfo.bitDepth == 16 ? (int) (d * 65535.0 + 0.5) : (int) (d * 255.0 + 0.5); // + } - public static double int2doubleClamped(ImageLineInt line, int p) { - // TODO: replace my multiplication? - double d = line.imgInfo.bitDepth == 16 ? p / 65535.0 : p / 255.0; - return d <= 0.0 ? 0 : (d >= 1.0 ? 1.0 : d); - } + public static int double2intClamped(final ImageLineInt line, double d) { + d = d <= 0.0 ? 0 : d >= 1.0 ? 1.0 : d; + return line.imgInfo.bitDepth == 16 ? (int) (d * 65535.0 + 0.5) : (int) (d * 255.0 + 0.5); // + } - public static int double2int(ImageLineInt line, double d) { - d = d <= 0.0 ? 0 : (d >= 1.0 ? 1.0 : d); - return line.imgInfo.bitDepth == 16 ? (int) (d * 65535.0 + 0.5) : (int) (d * 255.0 + 0.5); // - } + public static int clampTo_0_255(final int i) { + return i > 255 ? 255 : i < 0 ? 0 : i; + } - public static int double2intClamped(ImageLineInt line, double d) { - d = d <= 0.0 ? 0 : (d >= 1.0 ? 1.0 : d); - return line.imgInfo.bitDepth == 16 ? (int) (d * 65535.0 + 0.5) : (int) (d * 255.0 + 0.5); // - } + public static int clampTo_0_65535(final int i) { + return i > 65535 ? 65535 : i < 0 ? 0 : i; + } - public static int clampTo_0_255(int i) { - return i > 255 ? 255 : (i < 0 ? 0 : i); - } + public static int clampTo_128_127(final int x) { + return x > 127 ? 127 : x < -128 ? -128 : x; + } - public static int clampTo_0_65535(int i) { - return i > 65535 ? 65535 : (i < 0 ? 0 : i); - } + public static int getMaskForPackedFormats(final int bitDepth) { // Utility function for pack/unpack + if (bitDepth == 4) + return 0xf0; + else if (bitDepth == 2) + return 0xc0; + else + return 0x80; // bitDepth == 1 + } - public static int clampTo_128_127(int x) { - return x > 127 ? 127 : (x < -128 ? -128 : x); - } - - public static int getMaskForPackedFormats(int bitDepth) { // Utility function for pack/unpack - if (bitDepth == 4) - return 0xf0; - else if (bitDepth == 2) - return 0xc0; - else - return 0x80; // bitDepth == 1 - } - - public static int getMaskForPackedFormatsLs(int bitDepth) { // Utility function for pack/unpack - if (bitDepth == 4) - return 0x0f; - else if (bitDepth == 2) - return 0x03; - else - return 0x01; // bitDepth == 1 - } + public static int getMaskForPackedFormatsLs(final int bitDepth) { // Utility function for pack/unpack + if (bitDepth == 4) + return 0x0f; + else if (bitDepth == 2) + return 0x03; + else + return 0x01; // bitDepth == 1 + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/ImageLineInt.java b/teavm/src/main/java/ar/com/hjg/pngj/ImageLineInt.java index 2671276e..310ec132 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/ImageLineInt.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/ImageLineInt.java @@ -1,193 +1,203 @@ package ar.com.hjg.pngj; /** - * Represents an image line, integer format (one integer by sample). See {@link #scanline} to understand the format. + * Represents an image line, integer format (one integer by sample). See + * {@link #scanline} to understand the format. */ public class ImageLineInt implements IImageLine, IImageLineArray { - public final ImageInfo imgInfo; + public final ImageInfo imgInfo; - /** - * The 'scanline' is an array of integers, corresponds to an image line (row). - *

- * Each int is a "sample" (one for channel), (0-255 or 0-65535) in the corresponding PNG sequence: - * R G B R G B... or R G B A R G B A... - * or g g g ... or i i i (palette index) - *

- * For bitdepth=1/2/4 the value is not scaled (hence, eg, if bitdepth=2 the range will be 0-4) - *

- * To convert a indexed line to RGB values, see - * {@link ImageLineHelper#palette2rgb(ImageLineInt, ar.com.hjg.pngj.chunks.PngChunkPLTE, int[])} (you can't do the - * reverse) - */ - protected final int[] scanline; + /** + * The 'scanline' is an array of integers, corresponds to an image line + * (row). + *

+ * Each int is a "sample" (one for channel), (0-255 or 0-65535) + * in the corresponding PNG sequence: + * R G B R G B... or R G B A R G B A... + * or g g g ... or i i i (palette index) + *

+ * For bitdepth=1/2/4 the value is not scaled (hence, eg, if bitdepth=2 the + * range will be 0-4) + *

+ * To convert a indexed line to RGB values, see + * {@link ImageLineHelper#palette2rgb(ImageLineInt, ar.com.hjg.pngj.chunks.PngChunkPLTE, int[])} + * (you can't do the + * reverse) + */ + protected final int[] scanline; - /** - * number of elements in the scanline - */ - protected final int size; + /** + * number of elements in the scanline + */ + protected final int size; - /** - * informational ; only filled by the reader. not meaningful for interlaced - */ - protected FilterType filterType = FilterType.FILTER_UNKNOWN; + /** + * informational ; only filled by the reader. not meaningful for interlaced + */ + protected FilterType filterType = FilterType.FILTER_UNKNOWN; - /** - * @param imgInfo Inmutable ImageInfo, basic parameters of the image we are reading or writing - */ - public ImageLineInt(ImageInfo imgInfo) { - this(imgInfo, null); - } + /** + * @param imgInfo + * Inmutable ImageInfo, basic parameters of the image we are + * reading or writing + */ + public ImageLineInt(final ImageInfo imgInfo) { + this(imgInfo, null); + } - /** - * @param imgInfo Inmutable ImageInfo, basic parameters of the image we are reading or writing - * @param sci prealocated buffer (can be null) - */ - public ImageLineInt(ImageInfo imgInfo, int[] sci) { - this.imgInfo = imgInfo; - filterType = FilterType.FILTER_UNKNOWN; - size = imgInfo.samplesPerRow; - scanline = sci != null && sci.length >= size ? sci : new int[size]; - } + /** + * @param imgInfo + * Inmutable ImageInfo, basic parameters of the image we are + * reading or writing + * @param sci + * prealocated buffer (can be null) + */ + public ImageLineInt(final ImageInfo imgInfo, final int[] sci) { + this.imgInfo = imgInfo; + filterType = FilterType.FILTER_UNKNOWN; + size = imgInfo.samplesPerRow; + scanline = sci != null && sci.length >= size ? sci : new int[size]; + } - /** - * Helper method, returns a default factory for this object - * - */ - public static IImageLineFactory getFactory() { - return new IImageLineFactory() { - public ImageLineInt createImageLine(ImageInfo iminfo) { - return new ImageLineInt(iminfo); - } - }; - } + /** + * Helper method, returns a default factory for this object + * + */ + public static IImageLineFactory getFactory() { + return iminfo -> new ImageLineInt(iminfo); + } - public FilterType getFilterType() { - return filterType; - } + @Override + public FilterType getFilterType() { + return filterType; + } - /** - * This should rarely be used by client code. Only relevant if FilterPreserve==true - */ - public void setFilterType(FilterType ft) { - filterType = ft; - } + /** + * This should rarely be used by client code. Only relevant if + * FilterPreserve==true + */ + public void setFilterType(final FilterType ft) { + filterType = ft; + } - /** - * Basic info - */ - public String toString() { - return " cols=" + imgInfo.cols + " bpc=" + imgInfo.bitDepth + " size=" + scanline.length; - } + /** + * Basic info + */ + @Override + public String toString() { + return " cols=" + imgInfo.cols + " bpc=" + imgInfo.bitDepth + " size=" + scanline.length; + } - public void readFromPngRaw(byte[] raw, final int len, final int offset, final int step) { - setFilterType(FilterType.getByVal(raw[0])); - int len1 = len - 1; - int step1 = (step - 1) * imgInfo.channels; - if (imgInfo.bitDepth == 8) { - if (step == 1) {// 8bispp non-interlaced: most important case, should be optimized - for (int i = 0; i < size; i++) { - scanline[i] = (raw[i + 1] & 0xff); - } - } else {// 8bispp interlaced - for (int s = 1, c = 0, i = offset * imgInfo.channels; s <= len1; s++, i++) { - scanline[i] = (raw[s] & 0xff); - c++; - if (c == imgInfo.channels) { - c = 0; - i += step1; - } - } - } - } else if (imgInfo.bitDepth == 16) { - if (step == 1) {// 16bispp non-interlaced - for (int i = 0, s = 1; i < size; i++) { - scanline[i] = ((raw[s++] & 0xFF) << 8) | (raw[s++] & 0xFF); // 16 bitspc - } - } else { - for (int s = 1, c = 0, i = offset != 0 ? offset * imgInfo.channels : 0; s <= len1; s++, i++) { - scanline[i] = ((raw[s++] & 0xFF) << 8) | (raw[s] & 0xFF); // 16 bitspc - c++; - if (c == imgInfo.channels) { - c = 0; - i += step1; - } - } - } - } else { // packed formats - int mask0, mask, shi, bd; - bd = imgInfo.bitDepth; - mask0 = ImageLineHelper.getMaskForPackedFormats(bd); - for (int i = offset * imgInfo.channels, r = 1, c = 0; r < len; r++) { - mask = mask0; - shi = 8 - bd; - do { - scanline[i++] = (raw[r] & mask) >> shi; - mask >>= bd; - shi -= bd; - c++; - if (c == imgInfo.channels) { - c = 0; - i += step1; - } - } while (mask != 0 && i < size); - } - } - } + @Override + public void readFromPngRaw(final byte[] raw, final int len, final int offset, final int step) { + setFilterType(FilterType.getByVal(raw[0])); + final int len1 = len - 1; + final int step1 = (step - 1) * imgInfo.channels; + if (imgInfo.bitDepth == 8) { + if (step == 1) + for (int i = 0; i < size; i++) + scanline[i] = raw[i + 1] & 0xff; + else + for (int s = 1, c = 0, i = offset * imgInfo.channels; s <= len1; s++, i++) { + scanline[i] = raw[s] & 0xff; + c++; + if (c == imgInfo.channels) { + c = 0; + i += step1; + } + } + } else if (imgInfo.bitDepth == 16) { + if (step == 1) + for (int i = 0, s = 1; i < size; i++) + scanline[i] = (raw[s++] & 0xFF) << 8 | raw[s++] & 0xFF; // 16 bitspc + else + for (int s = 1, c = 0, i = offset != 0 ? offset * imgInfo.channels : 0; s <= len1; s++, i++) { + scanline[i] = (raw[s++] & 0xFF) << 8 | raw[s] & 0xFF; // 16 bitspc + c++; + if (c == imgInfo.channels) { + c = 0; + i += step1; + } + } + } else { // packed formats + int mask0, mask, shi, bd; + bd = imgInfo.bitDepth; + mask0 = ImageLineHelper.getMaskForPackedFormats(bd); + for (int i = offset * imgInfo.channels, r = 1, c = 0; r < len; r++) { + mask = mask0; + shi = 8 - bd; + do { + scanline[i++] = (raw[r] & mask) >> shi; + mask >>= bd; + shi -= bd; + c++; + if (c == imgInfo.channels) { + c = 0; + i += step1; + } + } while (mask != 0 && i < size); + } + } + } - public void writeToPngRaw(byte[] raw) { - raw[0] = (byte) filterType.val; - if (imgInfo.bitDepth == 8) { - for (int i = 0; i < size; i++) { - raw[i + 1] = (byte) scanline[i]; - } - } else if (imgInfo.bitDepth == 16) { - for (int i = 0, s = 1; i < size; i++) { - raw[s++] = (byte) (scanline[i] >> 8); - raw[s++] = (byte) (scanline[i] & 0xff); - } - } else { // packed formats - int shi, bd, v; - bd = imgInfo.bitDepth; - shi = 8 - bd; - v = 0; - for (int i = 0, r = 1; i < size; i++) { - v |= (scanline[i] << shi); - shi -= bd; - if (shi < 0 || i == size - 1) { - raw[r++] = (byte) v; - shi = 8 - bd; - v = 0; - } - } - } - } + @Override + public void writeToPngRaw(final byte[] raw) { + raw[0] = (byte) filterType.val; + if (imgInfo.bitDepth == 8) + for (int i = 0; i < size; i++) + raw[i + 1] = (byte) scanline[i]; + else if (imgInfo.bitDepth == 16) + for (int i = 0, s = 1; i < size; i++) { + raw[s++] = (byte) (scanline[i] >> 8); + raw[s++] = (byte) (scanline[i] & 0xff); + } + else { // packed formats + int shi, bd, v; + bd = imgInfo.bitDepth; + shi = 8 - bd; + v = 0; + for (int i = 0, r = 1; i < size; i++) { + v |= scanline[i] << shi; + shi -= bd; + if (shi < 0 || i == size - 1) { + raw[r++] = (byte) v; + shi = 8 - bd; + v = 0; + } + } + } + } - /** - * Does nothing in this implementation - */ - public void endReadFromPngRaw() { + /** + * Does nothing in this implementation + */ + @Override + public void endReadFromPngRaw() { - } + } - /** - * @see #size - */ - public int getSize() { - return size; - } + /** + * @see #size + */ + @Override + public int getSize() { + return size; + } - public int getElem(int i) { - return scanline[i]; - } + @Override + public int getElem(final int i) { + return scanline[i]; + } - /** - * @return see {@link #scanline} - */ - public int[] getScanline() { - return scanline; - } + /** + * @return see {@link #scanline} + */ + public int[] getScanline() { + return scanline; + } - public ImageInfo getImageInfo() { - return imgInfo; - } + @Override + public ImageInfo getImageInfo() { + return imgInfo; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/ImageLineSetDefault.java b/teavm/src/main/java/ar/com/hjg/pngj/ImageLineSetDefault.java index 4dbdce30..d1a1ed23 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/ImageLineSetDefault.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/ImageLineSetDefault.java @@ -6,146 +6,154 @@ import java.util.List; /** * Default implementation of {@link IImageLineSet}. *

- * Supports all modes: single cursor, full rows, or partial. This should not be used for + * Supports all modes: single cursor, full rows, or partial. This should not be + * used for */ public abstract class ImageLineSetDefault implements IImageLineSet { - protected final ImageInfo imgInfo; - private final boolean singleCursor; - private final int nlines, offset, step; - protected List imageLines; // null if single cursor - protected T imageLine; // null unless single cursor - protected int currentRow = -1; // only relevant (and not much) for cursor + protected final ImageInfo imgInfo; + private final boolean singleCursor; + private final int nlines, offset, step; + protected List imageLines; // null if single cursor + protected T imageLine; // null unless single cursor + protected int currentRow = -1; // only relevant (and not much) for cursor - public ImageLineSetDefault(ImageInfo imgInfo, final boolean singleCursor, final int nlinesx, - final int noffsetx, final int stepx) { - this.imgInfo = imgInfo; - this.singleCursor = singleCursor; - if (singleCursor) { - this.nlines = 1; // we store only one line, no matter how many will be read - offset = 0; - this.step = 1;// don't matter - } else { - this.nlines = nlinesx; // note that it can also be 1 - offset = noffsetx; - this.step = stepx;// don't matter - } - createImageLines(); - } + public ImageLineSetDefault(final ImageInfo imgInfo, final boolean singleCursor, final int nlinesx, final int noffsetx, final int stepx) { + this.imgInfo = imgInfo; + this.singleCursor = singleCursor; + if (singleCursor) { + this.nlines = 1; // we store only one line, no matter how many will be read + offset = 0; + this.step = 1;// don't matter + } else { + this.nlines = nlinesx; // note that it can also be 1 + offset = noffsetx; + this.step = stepx;// don't matter + } + createImageLines(); + } - private void createImageLines() { - if (singleCursor) - imageLine = createImageLine(); - else { - imageLines = new ArrayList(); - for (int i = 0; i < nlines; i++) - imageLines.add(createImageLine()); - } - } + private void createImageLines() { + if (singleCursor) + imageLine = createImageLine(); + else { + imageLines = new ArrayList<>(); + for (int i = 0; i < nlines; i++) + imageLines.add(createImageLine()); + } + } - protected abstract T createImageLine(); + protected abstract T createImageLine(); - /** - * Retrieves the image line - *

- * Warning: the argument is the row number in the original image - *

- * If this is a cursor, no check is done, always the same row is returned - */ - public T getImageLine(int n) { - currentRow = n; - if (singleCursor) - return imageLine; - else { - int r = imageRowToMatrixRowStrict(n); - if (r < 0) - throw new PngjException("Invalid row number"); - return imageLines.get(r); - } - } + /** + * Retrieves the image line + *

+ * Warning: the argument is the row number in the original image + *

+ * If this is a cursor, no check is done, always the same row is returned + */ + @Override + public T getImageLine(final int n) { + currentRow = n; + if (singleCursor) + return imageLine; + else { + final int r = imageRowToMatrixRowStrict(n); + if (r < 0) + throw new PngjException("Invalid row number"); + return imageLines.get(r); + } + } - /** - * does not check for valid range - */ - public T getImageLineRawNum(int r) { - if (singleCursor) - return imageLine; - else - return imageLines.get(r); - } + /** + * does not check for valid range + */ + @Override + public T getImageLineRawNum(final int r) { + if (singleCursor) + return imageLine; + else + return imageLines.get(r); + } - /** - * True if the set contains this image line - *

- * Warning: the argument is the row number in the original image - *

- * If this works as cursor, this returns true only if that is the number of its "current" line - */ - public boolean hasImageLine(int n) { - return singleCursor ? currentRow == n : imageRowToMatrixRowStrict(n) >= 0; - } + /** + * True if the set contains this image line + *

+ * Warning: the argument is the row number in the original image + *

+ * If this works as cursor, this returns true only if that is the number of + * its "current" line + */ + @Override + public boolean hasImageLine(final int n) { + return singleCursor ? currentRow == n : imageRowToMatrixRowStrict(n) >= 0; + } - /** - * How many lines does this object contain? - */ - public int size() { - return nlines; - } + /** + * How many lines does this object contain? + */ + @Override + public int size() { + return nlines; + } - /** - * Same as {@link #imageRowToMatrixRow(int)}, but returns negative if invalid - */ - public int imageRowToMatrixRowStrict(int imrow) { - imrow -= offset; - int mrow = imrow >= 0 && (step == 1 || imrow % step == 0) ? imrow / step : -1; - return mrow < nlines ? mrow : -1; - } + /** + * Same as {@link #imageRowToMatrixRow(int)}, but returns negative if + * invalid + */ + public int imageRowToMatrixRowStrict(int imrow) { + imrow -= offset; + final int mrow = imrow >= 0 && (step == 1 || imrow % step == 0) ? imrow / step : -1; + return mrow < nlines ? mrow : -1; + } - /** - * Converts from matrix row number (0 : nRows-1) to image row number - * - * @param mrow Matrix row number - * @return Image row number. Returns trash if mrow is invalid - */ - public int matrixRowToImageRow(int mrow) { - return mrow * step + offset; - } + /** + * Converts from matrix row number (0 : nRows-1) to image row number + * + * @param mrow + * Matrix row number + * @return Image row number. Returns trash if mrow is invalid + */ + public int matrixRowToImageRow(final int mrow) { + return mrow * step + offset; + } - /** - * Converts from real image row to this object row number. - *

- * Warning: this always returns a valid matrix row (clamping on 0 : nrows-1, and rounding down) - *

- * Eg: rowOffset=4,rowStep=2 imageRowToMatrixRow(17) returns 6 , imageRowToMatrixRow(1) returns 0 - */ - public int imageRowToMatrixRow(int imrow) { - int r = (imrow - offset) / step; - return r < 0 ? 0 : (r < nlines ? r : nlines - 1); - } + /** + * Converts from real image row to this object row number. + *

+ * Warning: this always returns a valid matrix row (clamping on 0 : nrows-1, + * and rounding down) + *

+ * Eg: rowOffset=4,rowStep=2 imageRowToMatrixRow(17) returns 6 , + * imageRowToMatrixRow(1) returns 0 + */ + public int imageRowToMatrixRow(final int imrow) { + final int r = (imrow - offset) / step; + return r < 0 ? 0 : r < nlines ? r : nlines - 1; + } - /** utility function, given a factory for one line, returns a factory for a set */ - public static IImageLineSetFactory createImageLineSetFactoryFromImageLineFactory( - final IImageLineFactory ifactory) { // ugly method must have ugly name. don't let this intimidate you - return new IImageLineSetFactory() { - public IImageLineSet create(final ImageInfo iminfo, boolean singleCursor, int nlines, - int noffset, int step) { - return new ImageLineSetDefault(iminfo, singleCursor, nlines, noffset, step) { - @Override - protected T createImageLine() { - return ifactory.createImageLine(iminfo); - } - }; - }; - }; - } + /** + * utility function, given a factory for one line, returns a factory for a + * set + */ + public static IImageLineSetFactory createImageLineSetFactoryFromImageLineFactory( + final IImageLineFactory ifactory) { // ugly method must have ugly name. don't let this intimidate you + return (iminfo, singleCursor, nlines, noffset, + step) -> new ImageLineSetDefault(iminfo, singleCursor, nlines, noffset, step) { + @Override + protected T createImageLine() { + return ifactory.createImageLine(iminfo); + } + }; + } - /** utility function, returns default factory for {@link ImageLineInt} */ - public static IImageLineSetFactory getFactoryInt() { - return createImageLineSetFactoryFromImageLineFactory(ImageLineInt.getFactory()); - } + /** utility function, returns default factory for {@link ImageLineInt} */ + public static IImageLineSetFactory getFactoryInt() { + return ImageLineSetDefault.createImageLineSetFactoryFromImageLineFactory(ImageLineInt.getFactory()); + } - /** utility function, returns default factory for {@link ImageLineByte} */ - public static IImageLineSetFactory getFactoryByte() { - return createImageLineSetFactoryFromImageLineFactory(ImageLineByte.getFactory()); - } + /** utility function, returns default factory for {@link ImageLineByte} */ + public static IImageLineSetFactory getFactoryByte() { + return ImageLineSetDefault.createImageLineSetFactoryFromImageLineFactory(ImageLineByte.getFactory()); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/PngHelperInternal.java b/teavm/src/main/java/ar/com/hjg/pngj/PngHelperInternal.java index 6785bdd4..79be507b 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/PngHelperInternal.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/PngHelperInternal.java @@ -16,314 +16,317 @@ import java.util.logging.Logger; */ public final class PngHelperInternal { - public static final String KEY_LOGGER = "ar.com.pngj"; - public static final Logger LOGGER = Logger.getLogger(KEY_LOGGER); + public static final String KEY_LOGGER = "ar.com.pngj"; + public static final Logger LOGGER = Logger.getLogger(PngHelperInternal.KEY_LOGGER); - /** - * Default charset, used internally by PNG for several things - */ - public static String charsetLatin1name = "UTF-8"; - public static Charset charsetLatin1 = Charset.forName(charsetLatin1name); - /** - * UTF-8 is only used for some chunks - */ - public static String charsetUTF8name = "UTF-8"; - public static Charset charsetUTF8 = Charset.forName(charsetUTF8name); + /** + * Default charset, used internally by PNG for several things + */ + public static String charsetLatin1name = "UTF-8"; + public static Charset charsetLatin1 = Charset.forName(PngHelperInternal.charsetLatin1name); + /** + * UTF-8 is only used for some chunks + */ + public static String charsetUTF8name = "UTF-8"; + public static Charset charsetUTF8 = Charset.forName(PngHelperInternal.charsetUTF8name); - private static ThreadLocal DEBUG = new ThreadLocal() { - protected Boolean initialValue() { - return Boolean.FALSE; - } - }; + private static ThreadLocal DEBUG = new ThreadLocal() { + @Override + protected Boolean initialValue() { + return Boolean.FALSE; + } + }; - /** - * PNG magic bytes - */ - public static byte[] getPngIdSignature() { - return new byte[] {-119, 80, 78, 71, 13, 10, 26, 10}; - } + /** + * PNG magic bytes + */ + public static byte[] getPngIdSignature() { + return new byte[] { -119, 80, 78, 71, 13, 10, 26, 10 }; + } - public static int doubleToInt100000(double d) { - return (int) (d * 100000.0 + 0.5); - } + public static int doubleToInt100000(final double d) { + return (int) (d * 100000.0 + 0.5); + } - public static double intToDouble100000(int i) { - return i / 100000.0; - } + public static double intToDouble100000(final int i) { + return i / 100000.0; + } - public static int readByte(InputStream is) { - try { - return is.read(); - } catch (IOException e) { - throw new PngjInputException("error reading byte", e); - } - } + public static int readByte(final InputStream is) { + try { + return is.read(); + } catch (final IOException e) { + throw new PngjInputException("error reading byte", e); + } + } - /** - * -1 if eof - * - * PNG uses "network byte order" - */ - public static int readInt2(InputStream is) { - try { - int b1 = is.read(); - int b2 = is.read(); - if (b1 == -1 || b2 == -1) - return -1; - return (b1 << 8) | b2; - } catch (IOException e) { - throw new PngjInputException("error reading Int2", e); - } - } + /** + * -1 if eof + * + * PNG uses "network byte order" + */ + public static int readInt2(final InputStream is) { + try { + final int b1 = is.read(); + final int b2 = is.read(); + if (b1 == -1 || b2 == -1) + return -1; + return b1 << 8 | b2; + } catch (final IOException e) { + throw new PngjInputException("error reading Int2", e); + } + } - /** - * -1 if eof - */ - public static int readInt4(InputStream is) { - try { - int b1 = is.read(); - int b2 = is.read(); - int b3 = is.read(); - int b4 = is.read(); - if (b1 == -1 || b2 == -1 || b3 == -1 || b4 == -1) - return -1; - return (b1 << 24) | (b2 << 16) | (b3 << 8) + b4; - } catch (IOException e) { - throw new PngjInputException("error reading Int4", e); - } - } + /** + * -1 if eof + */ + public static int readInt4(final InputStream is) { + try { + final int b1 = is.read(); + final int b2 = is.read(); + final int b3 = is.read(); + final int b4 = is.read(); + if (b1 == -1 || b2 == -1 || b3 == -1 || b4 == -1) + return -1; + return b1 << 24 | b2 << 16 | (b3 << 8) + b4; + } catch (final IOException e) { + throw new PngjInputException("error reading Int4", e); + } + } - public static int readInt1fromByte(byte[] b, int offset) { - return (b[offset] & 0xff); - } + public static int readInt1fromByte(final byte[] b, final int offset) { + return b[offset] & 0xff; + } - public static int readInt2fromBytes(byte[] b, int offset) { - return ((b[offset] & 0xff) << 8) | ((b[offset + 1] & 0xff)); - } + public static int readInt2fromBytes(final byte[] b, final int offset) { + return (b[offset] & 0xff) << 8 | b[offset + 1] & 0xff; + } - public static final int readInt4fromBytes(byte[] b, int offset) { - return ((b[offset] & 0xff) << 24) | ((b[offset + 1] & 0xff) << 16) - | ((b[offset + 2] & 0xff) << 8) | (b[offset + 3] & 0xff); - } + public static int readInt4fromBytes(final byte[] b, final int offset) { + return (b[offset] & 0xff) << 24 | (b[offset + 1] & 0xff) << 16 | (b[offset + 2] & 0xff) << 8 | b[offset + 3] & 0xff; + } - public static void writeByte(OutputStream os, byte b) { - try { - os.write(b); - } catch (IOException e) { - throw new PngjOutputException(e); - } - } + public static void writeByte(final OutputStream os, final byte b) { + try { + os.write(b); + } catch (final IOException e) { + throw new PngjOutputException(e); + } + } - public static void writeByte(OutputStream os, byte[] bs) { - try { - os.write(bs); - } catch (IOException e) { - throw new PngjOutputException(e); - } - } + public static void writeByte(final OutputStream os, final byte[] bs) { + try { + os.write(bs); + } catch (final IOException e) { + throw new PngjOutputException(e); + } + } - public static void writeInt2(OutputStream os, int n) { - byte[] temp = {(byte) ((n >> 8) & 0xff), (byte) (n & 0xff)}; - writeBytes(os, temp); - } + public static void writeInt2(final OutputStream os, final int n) { + final byte[] temp = { (byte) (n >> 8 & 0xff), (byte) (n & 0xff) }; + PngHelperInternal.writeBytes(os, temp); + } - public static void writeInt4(OutputStream os, int n) { - byte[] temp = new byte[4]; - writeInt4tobytes(n, temp, 0); - writeBytes(os, temp); - } + public static void writeInt4(final OutputStream os, final int n) { + final byte[] temp = new byte[4]; + PngHelperInternal.writeInt4tobytes(n, temp, 0); + PngHelperInternal.writeBytes(os, temp); + } - public static void writeInt2tobytes(int n, byte[] b, int offset) { - b[offset] = (byte) ((n >> 8) & 0xff); - b[offset + 1] = (byte) (n & 0xff); - } + public static void writeInt2tobytes(final int n, final byte[] b, final int offset) { + b[offset] = (byte) (n >> 8 & 0xff); + b[offset + 1] = (byte) (n & 0xff); + } - public static void writeInt4tobytes(int n, byte[] b, int offset) { - b[offset] = (byte) ((n >> 24) & 0xff); - b[offset + 1] = (byte) ((n >> 16) & 0xff); - b[offset + 2] = (byte) ((n >> 8) & 0xff); - b[offset + 3] = (byte) (n & 0xff); - } + public static void writeInt4tobytes(final int n, final byte[] b, final int offset) { + b[offset] = (byte) (n >> 24 & 0xff); + b[offset + 1] = (byte) (n >> 16 & 0xff); + b[offset + 2] = (byte) (n >> 8 & 0xff); + b[offset + 3] = (byte) (n & 0xff); + } + /** + * guaranteed to read exactly len bytes. throws error if it can't + */ + public static void readBytes(final InputStream is, final byte[] b, final int offset, final int len) { + if (len == 0) + return; + try { + int read = 0; + while (read < len) { + final int n = is.read(b, offset + read, len - read); + if (n < 1) + throw new PngjInputException("error reading bytes, " + n + " !=" + len); + read += n; + } + } catch (final IOException e) { + throw new PngjInputException("error reading", e); + } + } - /** - * guaranteed to read exactly len bytes. throws error if it can't - */ - public static void readBytes(InputStream is, byte[] b, int offset, int len) { - if (len == 0) - return; - try { - int read = 0; - while (read < len) { - int n = is.read(b, offset + read, len - read); - if (n < 1) - throw new PngjInputException("error reading bytes, " + n + " !=" + len); - read += n; - } - } catch (IOException e) { - throw new PngjInputException("error reading", e); - } - } + public static void skipBytes(final InputStream is, long len) { + try { + while (len > 0) { + final long n1 = is.skip(len); + if (n1 > 0) + len -= n1; + else if (n1 == 0) { // should we retry? lets read one byte + if (is.read() == -1) // EOF + break; + else + len--; + } else + // negative? this should never happen but... + throw new IOException("skip() returned a negative value ???"); + } + } catch (final IOException e) { + throw new PngjInputException(e); + } + } - public static void skipBytes(InputStream is, long len) { - try { - while (len > 0) { - long n1 = is.skip(len); - if (n1 > 0) { - len -= n1; - } else if (n1 == 0) { // should we retry? lets read one byte - if (is.read() == -1) // EOF - break; - else - len--; - } else - // negative? this should never happen but... - throw new IOException("skip() returned a negative value ???"); - } - } catch (IOException e) { - throw new PngjInputException(e); - } - } + public static void writeBytes(final OutputStream os, final byte[] b) { + try { + os.write(b); + } catch (final IOException e) { + throw new PngjOutputException(e); + } + } - public static void writeBytes(OutputStream os, byte[] b) { - try { - os.write(b); - } catch (IOException e) { - throw new PngjOutputException(e); - } - } + public static void writeBytes(final OutputStream os, final byte[] b, final int offset, final int n) { + try { + os.write(b, offset, n); + } catch (final IOException e) { + throw new PngjOutputException(e); + } + } - public static void writeBytes(OutputStream os, byte[] b, int offset, int n) { - try { - os.write(b, offset, n); - } catch (IOException e) { - throw new PngjOutputException(e); - } - } + public static void logdebug(final String msg) { + if (PngHelperInternal.isDebug()) + System.err.println("logdebug: " + msg); + } - public static void logdebug(String msg) { - if (isDebug()) - System.err.println("logdebug: " + msg); - } + // / filters + public static int filterRowNone(final int r) { + return r & 0xFF; + } - // / filters - public static int filterRowNone(int r) { - return (int) (r & 0xFF); - } + public static int filterRowSub(final int r, final int left) { + return r - left & 0xFF; + } - public static int filterRowSub(int r, int left) { - return ((int) (r - left) & 0xFF); - } + public static int filterRowUp(final int r, final int up) { + return r - up & 0xFF; + } - public static int filterRowUp(int r, int up) { - return ((int) (r - up) & 0xFF); - } + public static int filterRowAverage(final int r, final int left, final int up) { + return r - (left + up) / 2 & 0xFF; + } - public static int filterRowAverage(int r, int left, int up) { - return (r - (left + up) / 2) & 0xFF; - } + public static int filterRowPaeth(final int r, final int left, final int up, final int upleft) { // a = left, b = above, c + // = upper left + return r - PngHelperInternal.filterPaethPredictor(left, up, upleft) & 0xFF; + } - public static int filterRowPaeth(int r, int left, int up, int upleft) { // a = left, b = above, c - // = upper left - return (r - filterPaethPredictor(left, up, upleft)) & 0xFF; - } + static int filterPaethPredictor(final int a, final int b, final int c) { // a = left, b = + // above, c = upper + // left + // from http://www.libpng.org/pub/png/spec/1.2/PNG-Filters.html - final static int filterPaethPredictor(final int a, final int b, final int c) { // a = left, b = - // above, c = upper - // left - // from http://www.libpng.org/pub/png/spec/1.2/PNG-Filters.html + final int p = a + b - c;// ; initial estimate + final int pa = p >= a ? p - a : a - p; + final int pb = p >= b ? p - b : b - p; + final int pc = p >= c ? p - c : c - p; + // ; return nearest of a,b,c, + // ; breaking ties in order a,b,c. + if (pa <= pb && pa <= pc) + return a; + else if (pb <= pc) + return b; + else + return c; + } - final int p = a + b - c;// ; initial estimate - final int pa = p >= a ? p - a : a - p; - final int pb = p >= b ? p - b : b - p; - final int pc = p >= c ? p - c : c - p; - // ; return nearest of a,b,c, - // ; breaking ties in order a,b,c. - if (pa <= pb && pa <= pc) - return a; - else if (pb <= pc) - return b; - else - return c; - } + /** + * Prits a debug message (prints class name, method and line number) + * + * @param obj + * : Object to print + */ + public static void debug(final Object obj) { + PngHelperInternal.debug(obj, 1, true); + } - /** - * Prits a debug message (prints class name, method and line number) - * - * @param obj : Object to print - */ - public static void debug(Object obj) { - debug(obj, 1, true); - } + /** + * Prits a debug message (prints class name, method and line number) + * + * @param obj + * : Object to print + * @param offset + * : Offset N lines from stacktrace + */ + static void debug(final Object obj, final int offset) { + PngHelperInternal.debug(obj, offset, true); + } - /** - * Prits a debug message (prints class name, method and line number) - * - * @param obj : Object to print - * @param offset : Offset N lines from stacktrace - */ - static void debug(Object obj, int offset) { - debug(obj, offset, true); - } + public static InputStream istreamFromFile(final File f) { + FileInputStream is; + try { + is = new FileInputStream(f); + } catch (final Exception e) { + throw new PngjInputException("Could not open " + f, e); + } + return is; + } - public static InputStream istreamFromFile(File f) { - FileInputStream is; - try { - is = new FileInputStream(f); - } catch (Exception e) { - throw new PngjInputException("Could not open " + f, e); - } - return is; - } + static OutputStream ostreamFromFile(final File f) { + return PngHelperInternal.ostreamFromFile(f, true); + } - static OutputStream ostreamFromFile(File f) { - return ostreamFromFile(f, true); - } + static OutputStream ostreamFromFile(final File f, final boolean overwrite) { + return PngHelperInternal2.ostreamFromFile(f, overwrite); + } - static OutputStream ostreamFromFile(File f, boolean overwrite) { - return PngHelperInternal2.ostreamFromFile(f, overwrite); - } + /** + * Prints a debug message (prints class name, method and line number) to + * stderr and logFile + * + * @param obj + * : Object to print + * @param offset + * : Offset N lines from stacktrace + * @param newLine + * : Print a newline char at the end ('\n') + */ + static void debug(final Object obj, final int offset, final boolean newLine) { + final StackTraceElement ste = new Exception().getStackTrace()[1 + offset]; + String steStr = ste.getClassName(); + final int ind = steStr.lastIndexOf('.'); + steStr = steStr.substring(ind + 1); + steStr += "." + ste.getMethodName() + "(" + ste.getLineNumber() + "): " + (obj == null ? null : obj.toString()); + System.err.println(steStr); + } - /** - * Prints a debug message (prints class name, method and line number) to stderr and logFile - * - * @param obj : Object to print - * @param offset : Offset N lines from stacktrace - * @param newLine : Print a newline char at the end ('\n') - */ - static void debug(Object obj, int offset, boolean newLine) { - StackTraceElement ste = new Exception().getStackTrace()[1 + offset]; - String steStr = ste.getClassName(); - int ind = steStr.lastIndexOf('.'); - steStr = steStr.substring(ind + 1); - steStr += - "." + ste.getMethodName() + "(" + ste.getLineNumber() + "): " - + (obj == null ? null : obj.toString()); - System.err.println(steStr); - } + /** + * Sets a global debug flag. This is bound to a thread. + */ + public static void setDebug(final boolean b) { + PngHelperInternal.DEBUG.set(b); + } - /** - * Sets a global debug flag. This is bound to a thread. - */ - public static void setDebug(boolean b) { - DEBUG.set(b); - } + public static boolean isDebug() { + return PngHelperInternal.DEBUG.get().booleanValue(); + } - public static boolean isDebug() { - return DEBUG.get().booleanValue(); - } + public static long getDigest(final PngReader pngr) { + return pngr.getSimpleDigest(); + } - public static long getDigest(PngReader pngr) { - return pngr.getSimpleDigest(); - } + public static void initCrcForTests(final PngReader pngr) { + pngr.prepareSimpleDigestComputation(); + } - public static void initCrcForTests(PngReader pngr) { - pngr.prepareSimpleDigestComputation(); - } - - public static long getRawIdatBytes(PngReader r) { // in case of image with frames, returns the current one - return r.interlaced ? r.getChunkseq().getDeinterlacer().getTotalRawBytes() : r.getCurImgInfo() - .getTotalRawBytes(); - } + public static long getRawIdatBytes(final PngReader r) { // in case of image with frames, returns the current one + return r.interlaced ? r.getChunkseq().getDeinterlacer().getTotalRawBytes() : r.getCurImgInfo().getTotalRawBytes(); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/PngHelperInternal2.java b/teavm/src/main/java/ar/com/hjg/pngj/PngHelperInternal2.java index ab34ce15..58e702a8 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/PngHelperInternal2.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/PngHelperInternal2.java @@ -4,30 +4,32 @@ import java.io.File; import java.io.OutputStream; /** - * For organization purposes, this class is the onlt that uses classes not in GAE (Google App Engine) white list + * For organization purposes, this class is the onlt that uses classes not in + * GAE (Google App Engine) white list *

* You should not use this class in GAE */ final class PngHelperInternal2 { - /** - * WARNING: this uses FileOutputStream which is not allowed in GoogleAppEngine - * - * In GAE, dont use this - * - * @param f - * @param allowoverwrite - * @return - */ - static OutputStream ostreamFromFile(File f, boolean allowoverwrite) { - java.io.FileOutputStream os = null; // this will fail in GAE! - if (f.exists() && !allowoverwrite) - throw new PngjOutputException("File already exists: " + f); - try { - os = new java.io.FileOutputStream(f); - } catch (Exception e) { - throw new PngjInputException("Could not open for write" + f, e); - } - return os; - } + /** + * WARNING: this uses FileOutputStream which is not allowed in + * GoogleAppEngine + * + * In GAE, dont use this + * + * @param f + * @param allowoverwrite + * @return + */ + static OutputStream ostreamFromFile(final File f, final boolean allowoverwrite) { + java.io.FileOutputStream os = null; // this will fail in GAE! + if (f.exists() && !allowoverwrite) + throw new PngjOutputException("File already exists: " + f); + try { + os = new java.io.FileOutputStream(f); + } catch (final Exception e) { + throw new PngjInputException("Could not open for write" + f, e); + } + return os; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/PngReader.java b/teavm/src/main/java/ar/com/hjg/pngj/PngReader.java index 6367761c..efb5e9ad 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/PngReader.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/PngReader.java @@ -15,572 +15,633 @@ import ar.com.hjg.pngj.chunks.PngMetadata; /** * Reads a PNG image (pixels and/or metadata) from a file or stream. *

- * Each row is read as an {@link ImageLineInt} object (one int per sample), but this can be changed by setting a + * Each row is read as an {@link ImageLineInt} object (one int per sample), but + * this can be changed by setting a * different ImageLineFactory *

- * Internally, this wraps a {@link ChunkSeqReaderPng} with a {@link BufferedStreamFeeder} + * Internally, this wraps a {@link ChunkSeqReaderPng} with a + * {@link BufferedStreamFeeder} *

* The reading sequence is as follows:
- * 1. At construction time, the header and IHDR chunk are read (basic image info)
- * 2. Afterwards you can set some additional global options. Eg. {@link #setCrcCheckDisabled()}.
- * 3. Optional: If you call getMetadata() or getChunksLisk() before start reading the rows, all the chunks before IDAT + * 1. At construction time, the header and IHDR chunk are read (basic image + * info)
+ * 2. Afterwards you can set some additional global options. Eg. + * {@link #setCrcCheckDisabled()}.
+ * 3. Optional: If you call getMetadata() or getChunksLisk() before start + * reading the rows, all the chunks before IDAT * are then loaded and available
- * 4a. The rows are read in order by calling {@link #readRow()}. You can also call {@link #readRow(int)} to skip rows - * -but you can't go backwards, at least not with this implementation. This method returns a {@link IImageLine} object - * which can be casted to the concrete class. This class returns by default a {@link ImageLineInt}, but this can be + * 4a. The rows are read in order by calling {@link #readRow()}. You can also + * call {@link #readRow(int)} to skip rows + * -but you can't go backwards, at least not with this implementation. This + * method returns a {@link IImageLine} object + * which can be casted to the concrete class. This class returns by default a + * {@link ImageLineInt}, but this can be * changed.
- * 4b. Alternatively, you can read all rows, or a subset, in a single call: {@link #readRows()}, - * {@link #readRows(int, int, int)} ,etc. In general this consumes more memory, but for interlaced images this is + * 4b. Alternatively, you can read all rows, or a subset, in a single call: + * {@link #readRows()}, + * {@link #readRows(int, int, int)} ,etc. In general this consumes more memory, + * but for interlaced images this is * equally efficient, and more so if reading a small subset of rows.
- * 5. Reading of the last row automatically loads the trailing chunks, and ends the reader.
- * 6. end() also loads the trailing chunks, if not done, and finishes cleanly the reading and closes the stream. + * 5. Reading of the last row automatically loads the trailing chunks, and ends + * the reader.
+ * 6. end() also loads the trailing chunks, if not done, and finishes cleanly + * the reading and closes the stream. *

- * See also {@link PngReaderInt} (esentially the same as this, and slightly preferred) and {@link PngReaderByte} (uses + * See also {@link PngReaderInt} (esentially the same as this, and slightly + * preferred) and {@link PngReaderByte} (uses * byte instead of int to store the samples). */ public class PngReader { - // some performance/defensive limits - /** - * Defensive limit: refuse to read more than 900MB, can be changed with {@link #setMaxTotalBytesRead(long)} - */ - public static final long MAX_TOTAL_BYTES_READ_DEFAULT = 901001001L; // ~ 900MB + // some performance/defensive limits + /** + * Defensive limit: refuse to read more than 900MB, can be changed with + * {@link #setMaxTotalBytesRead(long)} + */ + public static final long MAX_TOTAL_BYTES_READ_DEFAULT = 901001001L; // ~ 900MB - /** - * Defensive limit: refuse to load more than 5MB of ancillary metadata, see {@link #setMaxBytesMetadata(long)} and - * also {@link #addChunkToSkip(String)} - */ - public static final long MAX_BYTES_METADATA_DEFAULT = 5024024; // for ancillary chunks + /** + * Defensive limit: refuse to load more than 5MB of ancillary metadata, see + * {@link #setMaxBytesMetadata(long)} and + * also {@link #addChunkToSkip(String)} + */ + public static final long MAX_BYTES_METADATA_DEFAULT = 5024024; // for ancillary chunks - /** - * Skip ancillary chunks greater than 2MB, see {@link #setSkipChunkMaxSize(long)} - */ - public static final long MAX_CHUNK_SIZE_SKIP = 2024024; // chunks exceeding this size will be skipped (nor even CRC - // checked) + /** + * Skip ancillary chunks greater than 2MB, see + * {@link #setSkipChunkMaxSize(long)} + */ + public static final long MAX_CHUNK_SIZE_SKIP = 2024024; // chunks exceeding this size will be skipped (nor even CRC + // checked) - /** - * Basic image info - final and inmutable. - */ - public final ImageInfo imgInfo; // People always told me: be careful what you do, and don't go around declaring public - // fields... - /** - * flag: image was in interlaced format - */ - public final boolean interlaced; + /** + * Basic image info - final and inmutable. + */ + public final ImageInfo imgInfo; // People always told me: be careful what you do, and don't go around declaring public + // fields... + /** + * flag: image was in interlaced format + */ + public final boolean interlaced; - /** - * This object has most of the intelligence to parse the chunks and decompress the IDAT stream - */ - protected final ChunkSeqReaderPng chunkseq; + /** + * This object has most of the intelligence to parse the chunks and + * decompress the IDAT stream + */ + protected final ChunkSeqReaderPng chunkseq; - /** - * Takes bytes from the InputStream and passes it to the ChunkSeqReaderPng. Never null. - */ - protected final BufferedStreamFeeder streamFeeder; + /** + * Takes bytes from the InputStream and passes it to the ChunkSeqReaderPng. + * Never null. + */ + protected final BufferedStreamFeeder streamFeeder; - /** - * @see #getMetadata() - */ - protected final PngMetadata metadata; // this a wrapper over chunks + /** + * @see #getMetadata() + */ + protected final PngMetadata metadata; // this a wrapper over chunks - /** - * Current row number (reading or read), numbered from 0 - */ - protected int rowNum = -1; + /** + * Current row number (reading or read), numbered from 0 + */ + protected int rowNum = -1; - /** - * Represents the set of lines (rows) being read. Normally this works as a cursor, storing only one (the current) row. - * This stores several (perhaps all) rows only if calling {@link #readRows()} or for interlaced images (this later is - * transparent to the user) - */ - protected IImageLineSet imlinesSet; + /** + * Represents the set of lines (rows) being read. Normally this works as a + * cursor, storing only one (the current) row. + * This stores several (perhaps all) rows only if calling + * {@link #readRows()} or for interlaced images (this later is + * transparent to the user) + */ + protected IImageLineSet imlinesSet; - /** - * This factory decides the concrete type of the ImageLine that will be used. See {@link ImageLineSetDefault} for - * examples - */ - private IImageLineSetFactory imageLineSetFactory; + /** + * This factory decides the concrete type of the ImageLine that will be + * used. See {@link ImageLineSetDefault} for + * examples + */ + private IImageLineSetFactory imageLineSetFactory; - CRC32 idatCrca;// for internal testing - Adler32 idatCrcb;// for internal testing + CRC32 idatCrca;// for internal testing + Adler32 idatCrcb;// for internal testing - /** - * Constructs a PngReader object from a stream, with default options. This reads the signature and the first IHDR - * chunk only. - *

- * Warning: In case of exception the stream is NOT closed. - *

- * Warning: By default the stream will be closed when this object is {@link #close()}d. See - * {@link #PngReader(InputStream,boolean)} or {@link #setShouldCloseStream(boolean)} - *

- * - * @param inputStream PNG stream - */ - public PngReader(InputStream inputStream) { - this(inputStream, true); - } + /** + * Constructs a PngReader object from a stream, with default options. This + * reads the signature and the first IHDR + * chunk only. + *

+ * Warning: In case of exception the stream is NOT closed. + *

+ * Warning: By default the stream will be closed when this object is + * {@link #close()}d. See + * {@link #PngReader(InputStream,boolean)} or + * {@link #setShouldCloseStream(boolean)} + *

+ * + * @param inputStream + * PNG stream + */ + public PngReader(final InputStream inputStream) { + this(inputStream, true); + } - /** - * Same as {@link #PngReader(InputStream)} but allows to specify early if the stream must be closed - * - * @param inputStream - * @param shouldCloseStream The stream will be closed in case of exception (constructor included) or normal - * termination. - */ - public PngReader(InputStream inputStream, boolean shouldCloseStream) { - streamFeeder = new BufferedStreamFeeder(inputStream); - streamFeeder.setCloseStream(shouldCloseStream); - chunkseq = createChunkSeqReader(); - try { - streamFeeder.setFailIfNoFeed(true); - if (!streamFeeder.feedFixed(chunkseq, 36)) // 8+13+12=36 PNG signature+IHDR chunk - throw new PngjInputException("error reading first 21 bytes"); - imgInfo = chunkseq.getImageInfo(); - interlaced = chunkseq.getDeinterlacer() != null; - setMaxBytesMetadata(MAX_BYTES_METADATA_DEFAULT); - setMaxTotalBytesRead(MAX_TOTAL_BYTES_READ_DEFAULT); - setSkipChunkMaxSize(MAX_CHUNK_SIZE_SKIP); - chunkseq.addChunkToSkip(PngChunkFDAT.ID);// default: skip fdAT chunks! - chunkseq.addChunkToSkip(PngChunkFCTL.ID);// default: skip fctl chunks! - this.metadata = new PngMetadata(chunkseq.chunksList); - // sets a default factory (with ImageLineInt), - // this can be overwriten by a extended constructor, or by a setter - setLineSetFactory(ImageLineSetDefault.getFactoryInt()); - rowNum = -1; - } catch (RuntimeException e) { - streamFeeder.close(); - chunkseq.close(); - throw e; - } - } + /** + * Same as {@link #PngReader(InputStream)} but allows to specify early if + * the stream must be closed + * + * @param inputStream + * @param shouldCloseStream + * The stream will be closed in case of exception (constructor + * included) or normal + * termination. + */ + public PngReader(final InputStream inputStream, final boolean shouldCloseStream) { + streamFeeder = new BufferedStreamFeeder(inputStream); + streamFeeder.setCloseStream(shouldCloseStream); + chunkseq = createChunkSeqReader(); + try { + streamFeeder.setFailIfNoFeed(true); + if (!streamFeeder.feedFixed(chunkseq, 36)) // 8+13+12=36 PNG signature+IHDR chunk + throw new PngjInputException("error reading first 21 bytes"); + imgInfo = chunkseq.getImageInfo(); + interlaced = chunkseq.getDeinterlacer() != null; + setMaxBytesMetadata(PngReader.MAX_BYTES_METADATA_DEFAULT); + setMaxTotalBytesRead(PngReader.MAX_TOTAL_BYTES_READ_DEFAULT); + setSkipChunkMaxSize(PngReader.MAX_CHUNK_SIZE_SKIP); + chunkseq.addChunkToSkip(PngChunkFDAT.ID);// default: skip fdAT chunks! + chunkseq.addChunkToSkip(PngChunkFCTL.ID);// default: skip fctl chunks! + metadata = new PngMetadata(chunkseq.chunksList); + // sets a default factory (with ImageLineInt), + // this can be overwriten by a extended constructor, or by a setter + setLineSetFactory(ImageLineSetDefault.getFactoryInt()); + rowNum = -1; + } catch (final RuntimeException e) { + streamFeeder.close(); + chunkseq.close(); + throw e; + } + } + /** + * Constructs a PngReader opening a file. Sets + * shouldCloseStream=true, so that the stream will be closed with + * this object. + * + * @param file + * PNG image file + */ + public PngReader(final File file) { + this(PngHelperInternal.istreamFromFile(file), true); + } - /** - * Constructs a PngReader opening a file. Sets shouldCloseStream=true, so that the stream will be closed with - * this object. - * - * @param file PNG image file - */ - public PngReader(File file) { - this(PngHelperInternal.istreamFromFile(file), true); - } + /** + * Reads chunks before first IDAT. Normally this is called automatically + *

+ * Position before: after IDHR (crc included) Position after: just after the + * first IDAT chunk id + *

+ * This can be called several times (tentatively), it does nothing if + * already run + *

+ * (Note: when should this be called? in the constructor? hardly, because we + * loose the opportunity to call + * setChunkLoadBehaviour() and perhaps other settings before reading the + * first row? but sometimes we want to access + * some metadata (plte, phys) before. Because of this, this method can be + * called explicitly but is also called + * implicititly in some methods (getMetatada(), getChunksList()) + */ + protected void readFirstChunks() { + while (chunkseq.currentChunkGroup < ChunksList.CHUNK_GROUP_4_IDAT) + if (streamFeeder.feed(chunkseq) <= 0) + throw new PngjInputException("premature ending reading first chunks"); + } + /** + * Determines which ancillary chunks (metadata) are to be loaded and which + * skipped. + *

+ * Additional restrictions may apply. See also + * {@link #setChunksToSkip(String...)}, {@link #addChunkToSkip(String)}, + * {@link #setMaxBytesMetadata(long)}, {@link #setSkipChunkMaxSize(long)} + * + * @param chunkLoadBehaviour + * {@link ChunkLoadBehaviour} + */ + public void setChunkLoadBehaviour(final ChunkLoadBehaviour chunkLoadBehaviour) { + chunkseq.setChunkLoadBehaviour(chunkLoadBehaviour); + } - /** - * Reads chunks before first IDAT. Normally this is called automatically - *

- * Position before: after IDHR (crc included) Position after: just after the first IDAT chunk id - *

- * This can be called several times (tentatively), it does nothing if already run - *

- * (Note: when should this be called? in the constructor? hardly, because we loose the opportunity to call - * setChunkLoadBehaviour() and perhaps other settings before reading the first row? but sometimes we want to access - * some metadata (plte, phys) before. Because of this, this method can be called explicitly but is also called - * implicititly in some methods (getMetatada(), getChunksList()) - */ - protected void readFirstChunks() { - while (chunkseq.currentChunkGroup < ChunksList.CHUNK_GROUP_4_IDAT) - if (streamFeeder.feed(chunkseq) <= 0) - throw new PngjInputException("premature ending reading first chunks"); - } + /** + * All loaded chunks (metada). If we have not yet end reading the image, + * this will include only the chunks before the + * pixels data (IDAT) + *

+ * Critical chunks are included, except that all IDAT chunks appearance are + * replaced by a single dummy-marker IDAT + * chunk. These might be copied to the PngWriter + *

+ * + * @see #getMetadata() + */ + public ChunksList getChunksList() { + return getChunksList(true); + } - /** - * Determines which ancillary chunks (metadata) are to be loaded and which skipped. - *

- * Additional restrictions may apply. See also {@link #setChunksToSkip(String...)}, {@link #addChunkToSkip(String)}, - * {@link #setMaxBytesMetadata(long)}, {@link #setSkipChunkMaxSize(long)} - * - * @param chunkLoadBehaviour {@link ChunkLoadBehaviour} - */ - public void setChunkLoadBehaviour(ChunkLoadBehaviour chunkLoadBehaviour) { - this.chunkseq.setChunkLoadBehaviour(chunkLoadBehaviour); - } + public ChunksList getChunksList(final boolean forceLoadingOfFirstChunks) { + if (forceLoadingOfFirstChunks && chunkseq.firstChunksNotYetRead()) + readFirstChunks(); + return chunkseq.chunksList; + } - /** - * All loaded chunks (metada). If we have not yet end reading the image, this will include only the chunks before the - * pixels data (IDAT) - *

- * Critical chunks are included, except that all IDAT chunks appearance are replaced by a single dummy-marker IDAT - * chunk. These might be copied to the PngWriter - *

- * - * @see #getMetadata() - */ - public ChunksList getChunksList() { - return getChunksList(true); - } + int getCurrentChunkGroup() { + return chunkseq.currentChunkGroup; + } - public ChunksList getChunksList(boolean forceLoadingOfFirstChunks) { - if (forceLoadingOfFirstChunks && chunkseq.firstChunksNotYetRead()) - readFirstChunks(); - return chunkseq.chunksList; - } + /** + * High level wrapper over chunksList + * + * @see #getChunksList() + */ + public PngMetadata getMetadata() { + if (chunkseq.firstChunksNotYetRead()) + readFirstChunks(); + return metadata; + } - int getCurrentChunkGroup() { - return chunkseq.currentChunkGroup; - } + /** + * Reads next row. + * + * The caller must know that there are more rows to read. + * + * @return Never null. Throws PngInputException if no more + */ + public IImageLine readRow() { + return readRow(rowNum + 1); + } - /** - * High level wrapper over chunksList - * - * @see #getChunksList() - */ - public PngMetadata getMetadata() { - if (chunkseq.firstChunksNotYetRead()) - readFirstChunks(); - return metadata; - } + /** + * True if last row has not yet been read + */ + public boolean hasMoreRows() { + return rowNum < getCurImgInfo().rows - 1; + } - /** - * Reads next row. - * - * The caller must know that there are more rows to read. - * - * @return Never null. Throws PngInputException if no more - */ - public IImageLine readRow() { - return readRow(rowNum + 1); - } + /** + * The row number is mostly meant as a check, the rows must be called in + * ascending order (not necessarily consecutive) + */ + public IImageLine readRow(final int nrow) { + if (chunkseq.firstChunksNotYetRead()) + readFirstChunks(); + if (!interlaced) { + if (imlinesSet == null) + imlinesSet = createLineSet(true, -1, 0, 1); + final IImageLine line = imlinesSet.getImageLine(nrow); + if (nrow == rowNum) + return line; // already read?? + else if (nrow < rowNum) + throw new PngjInputException("rows must be read in increasing order: " + nrow); + while (rowNum < nrow) { + while (!chunkseq.getIdatSet().isRowReady()) + if (streamFeeder.feed(chunkseq) < 1) + throw new PngjInputException("premature ending"); + rowNum++; + chunkseq.getIdatSet().updateCrcs(idatCrca, idatCrcb); + if (rowNum == nrow) { + line.readFromPngRaw(chunkseq.getIdatSet().getUnfilteredRow(), getCurImgInfo().bytesPerRow + 1, 0, 1); + line.endReadFromPngRaw(); + } + chunkseq.getIdatSet().advanceToNextRow(); + } + return line; + } else { // and now, for something completely different (interlaced!) + if (imlinesSet == null) { + imlinesSet = createLineSet(false, getCurImgInfo().rows, 0, 1); + loadAllInterlaced(getCurImgInfo().rows, 0, 1); + } + rowNum = nrow; + return imlinesSet.getImageLine(nrow); + } - /** - * True if last row has not yet been read - */ - public boolean hasMoreRows() { - return rowNum < getCurImgInfo().rows - 1; - } + } - /** - * The row number is mostly meant as a check, the rows must be called in ascending order (not necessarily consecutive) - */ - public IImageLine readRow(int nrow) { - if (chunkseq.firstChunksNotYetRead()) - readFirstChunks(); - if (!interlaced) { - if (imlinesSet == null) - imlinesSet = createLineSet(true, -1, 0, 1); - IImageLine line = imlinesSet.getImageLine(nrow); - if (nrow == rowNum) - return line; // already read?? - else if (nrow < rowNum) - throw new PngjInputException("rows must be read in increasing order: " + nrow); - while (rowNum < nrow) { - while (!chunkseq.getIdatSet().isRowReady()) - if (streamFeeder.feed(chunkseq) < 1) - throw new PngjInputException("premature ending"); - rowNum++; - chunkseq.getIdatSet().updateCrcs(idatCrca, idatCrcb); - if (rowNum == nrow) { - line.readFromPngRaw(chunkseq.getIdatSet().getUnfilteredRow(), - getCurImgInfo().bytesPerRow + 1, 0, 1); - line.endReadFromPngRaw(); - } - chunkseq.getIdatSet().advanceToNextRow(); - } - return line; - } else { // and now, for something completely different (interlaced!) - if (imlinesSet == null) { - imlinesSet = createLineSet(false, getCurImgInfo().rows, 0, 1); - loadAllInterlaced(getCurImgInfo().rows, 0, 1); - } - rowNum = nrow; - return imlinesSet.getImageLine(nrow); - } + /** + * Reads all rows in a ImageLineSet This is handy, but less memory-efficient + * (except for interlaced) + */ + public IImageLineSet readRows() { + return readRows(getCurImgInfo().rows, 0, 1); + } - } + /** + * Reads a subset of rows. + *

+ * This method should called once, and not be mixed with {@link #readRow()} + * + * @param nRows + * how many rows to read (default: imageInfo.rows; negative: + * autocompute) + * @param rowOffset + * rows to skip (default:0) + * @param rowStep + * step between rows to load( default:1) + */ + public IImageLineSet readRows(int nRows, final int rowOffset, final int rowStep) { + if (chunkseq.firstChunksNotYetRead()) + readFirstChunks(); + if (nRows < 0) + nRows = (getCurImgInfo().rows - rowOffset) / rowStep; + if (rowStep < 1 || rowOffset < 0 || nRows == 0 || nRows * rowStep + rowOffset > getCurImgInfo().rows) + throw new PngjInputException("bad args"); + if (rowNum >= rowOffset) + throw new PngjInputException("readRows cannot be mixed with readRow"); + imlinesSet = createLineSet(false, nRows, rowOffset, rowStep); + if (!interlaced) { + int m = -1; // last row already read in + while (m < nRows - 1) { + while (!chunkseq.getIdatSet().isRowReady()) + if (streamFeeder.feed(chunkseq) < 1) + throw new PngjInputException("Premature ending"); + rowNum++; + chunkseq.getIdatSet().updateCrcs(idatCrca, idatCrcb); + m = (rowNum - rowOffset) / rowStep; + if (rowNum >= rowOffset && rowStep * m + rowOffset == rowNum) { + final IImageLine line = imlinesSet.getImageLine(rowNum); + line.readFromPngRaw(chunkseq.getIdatSet().getUnfilteredRow(), getCurImgInfo().bytesPerRow + 1, 0, 1); + line.endReadFromPngRaw(); + } + chunkseq.getIdatSet().advanceToNextRow(); + } + } else + loadAllInterlaced(nRows, rowOffset, rowStep); + chunkseq.getIdatSet().done(); + return imlinesSet; + } - /** - * Reads all rows in a ImageLineSet This is handy, but less memory-efficient (except for interlaced) - */ - public IImageLineSet readRows() { - return readRows(getCurImgInfo().rows, 0, 1); - } + /** + * Sets the factory that creates the ImageLine. By default, this + * implementation uses ImageLineInt but this can be + * changed (at construction time or later) by calling this method. + *

+ * See also {@link #createLineSet(boolean, int, int, int)} + * + * @param factory + */ + public void setLineSetFactory(final IImageLineSetFactory factory) { + imageLineSetFactory = factory; + } - /** - * Reads a subset of rows. - *

- * This method should called once, and not be mixed with {@link #readRow()} - * - * @param nRows how many rows to read (default: imageInfo.rows; negative: autocompute) - * @param rowOffset rows to skip (default:0) - * @param rowStep step between rows to load( default:1) - */ - public IImageLineSet readRows(int nRows, int rowOffset, int rowStep) { - if (chunkseq.firstChunksNotYetRead()) - readFirstChunks(); - if (nRows < 0) - nRows = (getCurImgInfo().rows - rowOffset) / rowStep; - if (rowStep < 1 || rowOffset < 0 || nRows == 0 - || nRows * rowStep + rowOffset > getCurImgInfo().rows) - throw new PngjInputException("bad args"); - if (rowNum >= rowOffset) - throw new PngjInputException("readRows cannot be mixed with readRow"); - imlinesSet = createLineSet(false, nRows, rowOffset, rowStep); - if (!interlaced) { - int m = -1; // last row already read in - while (m < nRows - 1) { - while (!chunkseq.getIdatSet().isRowReady()) - if (streamFeeder.feed(chunkseq) < 1) - throw new PngjInputException("Premature ending"); - rowNum++; - chunkseq.getIdatSet().updateCrcs(idatCrca, idatCrcb); - m = (rowNum - rowOffset) / rowStep; - if (rowNum >= rowOffset && rowStep * m + rowOffset == rowNum) { - IImageLine line = imlinesSet.getImageLine(rowNum); - line.readFromPngRaw(chunkseq.getIdatSet().getUnfilteredRow(), - getCurImgInfo().bytesPerRow + 1, 0, 1); - line.endReadFromPngRaw(); - } - chunkseq.getIdatSet().advanceToNextRow(); - } - } else { // and now, for something completely different (interlaced) - loadAllInterlaced(nRows, rowOffset, rowStep); - } - chunkseq.getIdatSet().done(); - return imlinesSet; - } + /** + * By default this uses the factory (which, by default creates + * ImageLineInt). You should rarely override this. + *

+ * See doc in + * {@link IImageLineSetFactory#create(ImageInfo, boolean, int, int, int)} + */ + protected IImageLineSet createLineSet(final boolean singleCursor, final int nlines, + final int noffset, final int step) { + return imageLineSetFactory.create(getCurImgInfo(), singleCursor, nlines, noffset, step); + } - /** - * Sets the factory that creates the ImageLine. By default, this implementation uses ImageLineInt but this can be - * changed (at construction time or later) by calling this method. - *

- * See also {@link #createLineSet(boolean, int, int, int)} - * - * @param factory - */ - public void setLineSetFactory(IImageLineSetFactory factory) { - imageLineSetFactory = factory; - } + protected void loadAllInterlaced(final int nRows, final int rowOffset, final int rowStep) { + final IdatSet idat = chunkseq.getIdatSet(); + int nread = 0; + do { + while (!chunkseq.getIdatSet().isRowReady()) + if (streamFeeder.feed(chunkseq) <= 0) + break; + if (!chunkseq.getIdatSet().isRowReady()) + throw new PngjInputException("Premature ending?"); + chunkseq.getIdatSet().updateCrcs(idatCrca, idatCrcb); + final int rowNumreal = idat.rowinfo.rowNreal; + final boolean inset = imlinesSet.hasImageLine(rowNumreal); + if (inset) { + imlinesSet.getImageLine(rowNumreal).readFromPngRaw(idat.getUnfilteredRow(), idat.rowinfo.buflen, idat.rowinfo.oX, idat.rowinfo.dX); + nread++; + } + idat.advanceToNextRow(); + } while (nread < nRows || !idat.isDone()); + idat.done(); + for (int i = 0, j = rowOffset; i < nRows; i++, j += rowStep) + imlinesSet.getImageLine(j).endReadFromPngRaw(); + } - /** - * By default this uses the factory (which, by default creates ImageLineInt). You should rarely override this. - *

- * See doc in {@link IImageLineSetFactory#create(ImageInfo, boolean, int, int, int)} - */ - protected IImageLineSet createLineSet(boolean singleCursor, int nlines, - int noffset, int step) { - return imageLineSetFactory.create(getCurImgInfo(), singleCursor, nlines, noffset, step); - } + /** + * Reads all the (remaining) file, skipping the pixels data. This is much + * more efficient that calling + * {@link #readRow()}, specially for big files (about 10 times faster!), + * because it doesn't even decompress the IDAT + * stream and disables CRC check Use this if you are not interested in + * reading pixels,only metadata. + */ + public void readSkippingAllRows() { + chunkseq.addChunkToSkip(PngChunkIDAT.ID); + chunkseq.addChunkToSkip(PngChunkFDAT.ID); + if (chunkseq.firstChunksNotYetRead()) + readFirstChunks(); + end(); + } - protected void loadAllInterlaced(int nRows, int rowOffset, int rowStep) { - IdatSet idat = chunkseq.getIdatSet(); - int nread = 0; - do { - while (!chunkseq.getIdatSet().isRowReady()) - if (streamFeeder.feed(chunkseq) <= 0) - break; - if (!chunkseq.getIdatSet().isRowReady()) - throw new PngjInputException("Premature ending?"); - chunkseq.getIdatSet().updateCrcs(idatCrca, idatCrcb); - int rowNumreal = idat.rowinfo.rowNreal; - boolean inset = imlinesSet.hasImageLine(rowNumreal); - if (inset) { - imlinesSet.getImageLine(rowNumreal).readFromPngRaw(idat.getUnfilteredRow(), - idat.rowinfo.buflen, idat.rowinfo.oX, idat.rowinfo.dX); - nread++; - } - idat.advanceToNextRow(); - } while (nread < nRows || !idat.isDone()); - idat.done(); - for (int i = 0, j = rowOffset; i < nRows; i++, j += rowStep) { - imlinesSet.getImageLine(j).endReadFromPngRaw(); - } - } + /** + * Set total maximum bytes to read (0: unlimited; default: 200MB).
+ * These are the bytes read (not loaded) in the input stream. If exceeded, + * an exception will be thrown. + */ + public void setMaxTotalBytesRead(final long maxTotalBytesToRead) { + chunkseq.setMaxTotalBytesRead(maxTotalBytesToRead); + } - /** - * Reads all the (remaining) file, skipping the pixels data. This is much more efficient that calling - * {@link #readRow()}, specially for big files (about 10 times faster!), because it doesn't even decompress the IDAT - * stream and disables CRC check Use this if you are not interested in reading pixels,only metadata. - */ - public void readSkippingAllRows() { - chunkseq.addChunkToSkip(PngChunkIDAT.ID); - chunkseq.addChunkToSkip(PngChunkFDAT.ID); - if (chunkseq.firstChunksNotYetRead()) - readFirstChunks(); - end(); - } + /** + * Set total maximum bytes to load from ancillary chunks (0: unlimited; + * default: 5Mb).
+ * If exceeded, some chunks will be skipped + */ + public void setMaxBytesMetadata(final long maxBytesMetadata) { + chunkseq.setMaxBytesMetadata(maxBytesMetadata); + } - /** - * Set total maximum bytes to read (0: unlimited; default: 200MB).
- * These are the bytes read (not loaded) in the input stream. If exceeded, an exception will be thrown. - */ - public void setMaxTotalBytesRead(long maxTotalBytesToRead) { - chunkseq.setMaxTotalBytesRead(maxTotalBytesToRead); - } + /** + * Set maximum size in bytes for individual ancillary chunks (0: unlimited; + * default: 2MB).
+ * Chunks exceeding this length will be skipped (the CRC will not be + * checked) and the chunk will be saved as a + * PngChunkSkipped object. See also setSkipChunkIds + */ + public void setSkipChunkMaxSize(final long skipChunkMaxSize) { + chunkseq.setSkipChunkMaxSize(skipChunkMaxSize); + } - /** - * Set total maximum bytes to load from ancillary chunks (0: unlimited; default: 5Mb).
- * If exceeded, some chunks will be skipped - */ - public void setMaxBytesMetadata(long maxBytesMetadata) { - chunkseq.setMaxBytesMetadata(maxBytesMetadata); - } + /** + * Chunks ids to be skipped.
+ * These chunks will be skipped (the CRC will not be checked) and the chunk + * will be saved as a PngChunkSkipped object. + * See also setSkipChunkMaxSize + */ + public void setChunksToSkip(final String... chunksToSkip) { + chunkseq.setChunksToSkip(chunksToSkip); + } - /** - * Set maximum size in bytes for individual ancillary chunks (0: unlimited; default: 2MB).
- * Chunks exceeding this length will be skipped (the CRC will not be checked) and the chunk will be saved as a - * PngChunkSkipped object. See also setSkipChunkIds - */ - public void setSkipChunkMaxSize(long skipChunkMaxSize) { - chunkseq.setSkipChunkMaxSize(skipChunkMaxSize); - } + public void addChunkToSkip(final String chunkToSkip) { + chunkseq.addChunkToSkip(chunkToSkip); + } - /** - * Chunks ids to be skipped.
- * These chunks will be skipped (the CRC will not be checked) and the chunk will be saved as a PngChunkSkipped object. - * See also setSkipChunkMaxSize - */ - public void setChunksToSkip(String... chunksToSkip) { - chunkseq.setChunksToSkip(chunksToSkip); - } + public void dontSkipChunk(final String chunkToSkip) { + chunkseq.dontSkipChunk(chunkToSkip); + } - public void addChunkToSkip(String chunkToSkip) { - chunkseq.addChunkToSkip(chunkToSkip); - } + /** + * if true, input stream will be closed after ending read + *

+ * default=true + */ + public void setShouldCloseStream(final boolean shouldCloseStream) { + streamFeeder.setCloseStream(shouldCloseStream); + } - public void dontSkipChunk(String chunkToSkip) { - chunkseq.dontSkipChunk(chunkToSkip); - } + /** + * Reads till end of PNG stream and call close() + * + * This should normally be called after reading the pixel data, to read the + * trailing chunks and close the stream. But + * it can be called at anytime. This will also read the first chunks if not + * still read, and skip pixels (IDAT) if + * still pending. + * + * If you want to read all metadata skipping pixels, readSkippingAllRows() + * is a little more efficient. + * + * If you want to abort immediately, call instead close() + */ + public void end() { + try { + if (chunkseq.firstChunksNotYetRead()) + readFirstChunks(); + if (chunkseq.getIdatSet() != null && !chunkseq.getIdatSet().isDone()) + chunkseq.getIdatSet().done(); + while (!chunkseq.isDone()) + if (streamFeeder.feed(chunkseq) <= 0) + break; + } finally { + close(); + } + } + /** + * Releases resources, and closes stream if corresponds. Idempotent, secure, + * no exceptions. + * + * This can be also called for abort. It is recommended to call this in case + * of exceptions + */ + public void close() { + try { + if (chunkseq != null) + chunkseq.close(); + } catch (final Exception e) { + PngHelperInternal.LOGGER.warning("error closing chunk sequence:" + e.getMessage()); + } + if (streamFeeder != null) + streamFeeder.close(); + } - /** - * if true, input stream will be closed after ending read - *

- * default=true - */ - public void setShouldCloseStream(boolean shouldCloseStream) { - streamFeeder.setCloseStream(shouldCloseStream); - } + /** + * Interlaced PNG is accepted -though not welcomed- now... + */ + public boolean isInterlaced() { + return interlaced; + } - /** - * Reads till end of PNG stream and call close() - * - * This should normally be called after reading the pixel data, to read the trailing chunks and close the stream. But - * it can be called at anytime. This will also read the first chunks if not still read, and skip pixels (IDAT) if - * still pending. - * - * If you want to read all metadata skipping pixels, readSkippingAllRows() is a little more efficient. - * - * If you want to abort immediately, call instead close() - */ - public void end() { - try { - if (chunkseq.firstChunksNotYetRead()) - readFirstChunks(); - if (chunkseq.getIdatSet() != null && !chunkseq.getIdatSet().isDone()) - chunkseq.getIdatSet().done(); - while (!chunkseq.isDone()) - if (streamFeeder.feed(chunkseq) <= 0) - break; - } finally { - close(); - } - } + /** + * Disables the CRC integrity check in IDAT chunks and ancillary chunks, + * this gives a slight increase in reading speed + * for big files + */ + public void setCrcCheckDisabled() { + chunkseq.setCheckCrc(false); + } - /** - * Releases resources, and closes stream if corresponds. Idempotent, secure, no exceptions. - * - * This can be also called for abort. It is recommended to call this in case of exceptions - */ - public void close() { - try { - if (chunkseq != null) - chunkseq.close(); - } catch (Exception e) { - PngHelperInternal.LOGGER.warning("error closing chunk sequence:" + e.getMessage()); - } - if (streamFeeder != null) - streamFeeder.close(); - } + /** + * Gets wrapped {@link ChunkSeqReaderPng} object + */ + public ChunkSeqReaderPng getChunkseq() { + return chunkseq; + } - /** - * Interlaced PNG is accepted -though not welcomed- now... - */ - public boolean isInterlaced() { - return interlaced; - } + /** + * called on construction time. Override if you want an alternative class + */ + protected ChunkSeqReaderPng createChunkSeqReader() { + return new ChunkSeqReaderPng(false); + } - /** - * Disables the CRC integrity check in IDAT chunks and ancillary chunks, this gives a slight increase in reading speed - * for big files - */ - public void setCrcCheckDisabled() { - chunkseq.setCheckCrc(false); - } + /** + * Enables and prepare the simple digest computation. Must be called before + * reading the pixels. See + * {@link #getSimpleDigestHex()} + */ + public void prepareSimpleDigestComputation() { + if (idatCrca == null) + idatCrca = new CRC32(); + else + idatCrca.reset(); + if (idatCrcb == null) + idatCrcb = new Adler32(); + else + idatCrcb.reset(); + imgInfo.updateCrc(idatCrca); + idatCrcb.update((byte) imgInfo.rows); // not important + } - /** - * Gets wrapped {@link ChunkSeqReaderPng} object - */ - public ChunkSeqReaderPng getChunkseq() { - return chunkseq; - } + long getSimpleDigest() { + if (idatCrca == null) + return 0; + else + return idatCrca.getValue() ^ idatCrcb.getValue() << 31; + } - /** called on construction time. Override if you want an alternative class */ - protected ChunkSeqReaderPng createChunkSeqReader() { - return new ChunkSeqReaderPng(false); - } + /** + * Pseudo 64-bits digest computed over the basic image properties and the + * raw pixels data: it should coincide for + * equivalent images encoded with different filters and compressors; but + * will not coincide for + * interlaced/non-interlaced; also, this does not take into account the + * palette info. This will be valid only if + * {@link #prepareSimpleDigestComputation()} has been called, and all rows + * have been read. Not fool-proof, not + * cryptografically secure, only for informal testing and duplicates + * detection. + * + * @return A 64-digest in hexadecimal + */ + public String getSimpleDigestHex() { + return String.format("%016X", getSimpleDigest()); + } + /** + * Basic info, for debugging. + */ + @Override + public String toString() { // basic info + return imgInfo.toString() + " interlaced=" + interlaced; + } - /** - * Enables and prepare the simple digest computation. Must be called before reading the pixels. See - * {@link #getSimpleDigestHex()} - */ - public void prepareSimpleDigestComputation() { - if (idatCrca == null) - idatCrca = new CRC32(); - else - idatCrca.reset(); - if (idatCrcb == null) - idatCrcb = new Adler32(); - else - idatCrcb.reset(); - imgInfo.updateCrc(idatCrca); - idatCrcb.update((byte) imgInfo.rows); // not important - } - - long getSimpleDigest() { - if (idatCrca == null) - return 0; - else - return (idatCrca.getValue() ^ (idatCrcb.getValue() << 31)); - } - - /** - * Pseudo 64-bits digest computed over the basic image properties and the raw pixels data: it should coincide for - * equivalent images encoded with different filters and compressors; but will not coincide for - * interlaced/non-interlaced; also, this does not take into account the palette info. This will be valid only if - * {@link #prepareSimpleDigestComputation()} has been called, and all rows have been read. Not fool-proof, not - * cryptografically secure, only for informal testing and duplicates detection. - * - * @return A 64-digest in hexadecimal - */ - public String getSimpleDigestHex() { - return String.format("%016X", getSimpleDigest()); - } - - /** - * Basic info, for debugging. - */ - public String toString() { // basic info - return imgInfo.toString() + " interlaced=" + interlaced; - } - - /** - * Basic info, in a compact format, apt for scripting COLSxROWS[dBITDEPTH][a][p][g][i] ( the default dBITDEPTH='d8' is - * ommited) - * - */ - public String toStringCompact() { - return imgInfo.toStringBrief() + (interlaced ? "i" : ""); - } - - public ImageInfo getImgInfo() { - return imgInfo; - } - - public ImageInfo getCurImgInfo() { - return chunkseq.getCurImgInfo(); - } + /** + * Basic info, in a compact format, apt for scripting + * COLSxROWS[dBITDEPTH][a][p][g][i] ( the default dBITDEPTH='d8' is + * ommited) + * + */ + public String toStringCompact() { + return imgInfo.toStringBrief() + (interlaced ? "i" : ""); + } + public ImageInfo getImgInfo() { + return imgInfo; + } + public ImageInfo getCurImgInfo() { + return chunkseq.getCurImgInfo(); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/PngReaderApng.java b/teavm/src/main/java/ar/com/hjg/pngj/PngReaderApng.java index 105edab7..14b54e76 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/PngReaderApng.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/PngReaderApng.java @@ -14,200 +14,198 @@ import ar.com.hjg.pngj.chunks.PngChunkIDAT; */ public class PngReaderApng extends PngReaderByte { - public PngReaderApng(File file) { - super(file); - dontSkipChunk(PngChunkFCTL.ID); - } + public PngReaderApng(final File file) { + super(file); + dontSkipChunk(PngChunkFCTL.ID); + } - public PngReaderApng(InputStream inputStream) { - super(inputStream); - dontSkipChunk(PngChunkFCTL.ID); - } + public PngReaderApng(final InputStream inputStream) { + super(inputStream); + dontSkipChunk(PngChunkFCTL.ID); + } - private Boolean apngKind = null; - private boolean firsIdatApngFrame = false; - protected PngChunkACTL actlChunk; // null if not APNG - private PngChunkFCTL fctlChunk; // current (null for the pseudo still frame) + private Boolean apngKind = null; + private boolean firsIdatApngFrame = false; + protected PngChunkACTL actlChunk; // null if not APNG + private PngChunkFCTL fctlChunk; // current (null for the pseudo still frame) - /** - * Current frame number (reading or read). First animated frame is 0. Frame -1 represents the IDAT (default image) - * when it's not part of the animation - */ - protected int frameNum = -1; // incremented after each fctl finding + /** + * Current frame number (reading or read). First animated frame is 0. Frame + * -1 represents the IDAT (default image) + * when it's not part of the animation + */ + protected int frameNum = -1; // incremented after each fctl finding - public boolean isApng() { - if (apngKind == null) { - // this triggers the loading of first chunks; - actlChunk = (PngChunkACTL) getChunksList().getById1(PngChunkACTL.ID); // null if not apng - apngKind = actlChunk != null; - firsIdatApngFrame = fctlChunk != null; + public boolean isApng() { + if (apngKind == null) { + // this triggers the loading of first chunks; + actlChunk = (PngChunkACTL) getChunksList().getById1(PngChunkACTL.ID); // null if not apng + apngKind = actlChunk != null; + firsIdatApngFrame = fctlChunk != null; - } - return apngKind.booleanValue(); - } + } + return apngKind.booleanValue(); + } + public void advanceToFrame(final int frame) { + if (frame < frameNum) + throw new PngjInputException("Cannot go backwards"); + if (frame >= getApngNumFrames()) + throw new PngjInputException("Frame out of range " + frame); + if (frame > frameNum) { + addChunkToSkip(PngChunkIDAT.ID); + addChunkToSkip(PngChunkFDAT.ID); + if (chunkseq.getIdatSet() != null && !chunkseq.getIdatSet().isDone()) + chunkseq.getIdatSet().done(); // seems to be necessary sometimes (we should check this) + while (frameNum < frame & !chunkseq.isDone()) + if (streamFeeder.feed(chunkseq) <= 0) + break; + } + if (frame == frameNum) { // prepare to read rows. at this point we have a new + dontSkipChunk(PngChunkIDAT.ID); + dontSkipChunk(PngChunkFDAT.ID); + rowNum = -1; + imlinesSet = null;// force recreation (this is slightly dirty) + // seek the next IDAT/fDAT - TODO: set the expected sequence number + while (!chunkseq.isDone() && !chunkseq.getCurChunkReader().isFromDeflatedSet()) + if (streamFeeder.feed(chunkseq) <= 0) + break; + } else + throw new PngjInputException("unexpected error seeking from frame " + frame); + } - public void advanceToFrame(int frame) { - if (frame < frameNum) - throw new PngjInputException("Cannot go backwards"); - if (frame >= getApngNumFrames()) - throw new PngjInputException("Frame out of range " + frame); - if (frame > frameNum) { - addChunkToSkip(PngChunkIDAT.ID); - addChunkToSkip(PngChunkFDAT.ID); - if (chunkseq.getIdatSet() != null && !chunkseq.getIdatSet().isDone()) - chunkseq.getIdatSet().done(); // seems to be necessary sometimes (we should check this) - while (frameNum < frame & !chunkseq.isDone()) - if (streamFeeder.feed(chunkseq) <= 0) - break; - } - if (frame == frameNum) { // prepare to read rows. at this point we have a new - dontSkipChunk(PngChunkIDAT.ID); - dontSkipChunk(PngChunkFDAT.ID); - rowNum = -1; - imlinesSet = null;// force recreation (this is slightly dirty) - // seek the next IDAT/fDAT - TODO: set the expected sequence number - while (!chunkseq.isDone() && !chunkseq.getCurChunkReader().isFromDeflatedSet()) - if (streamFeeder.feed(chunkseq) <= 0) - break; - } else { - throw new PngjInputException("unexpected error seeking from frame " + frame); - } - } + /** + * True if it has a default image (IDAT) that is not part of the animation. + * In that case, we consider it as a + * pseudo-frame (number -1) + */ + public boolean hasExtraStillImage() { + return isApng() && !firsIdatApngFrame; + } - /** - * True if it has a default image (IDAT) that is not part of the animation. In that case, we consider it as a - * pseudo-frame (number -1) - */ - public boolean hasExtraStillImage() { - return isApng() && !firsIdatApngFrame; - } + /** + * Only counts true animation frames. + */ + public int getApngNumFrames() { + if (isApng()) + return actlChunk.getNumFrames(); + else + return 0; + } - /** - * Only counts true animation frames. - */ - public int getApngNumFrames() { - if (isApng()) - return actlChunk.getNumFrames(); - else - return 0; - } + /** + * 0 if it's to been played infinitely. -1 if not APNG + */ + public int getApngNumPlays() { + if (isApng()) + return actlChunk.getNumPlays(); + else + return -1; + } - /** - * 0 if it's to been played infinitely. -1 if not APNG - */ - public int getApngNumPlays() { - if (isApng()) - return actlChunk.getNumPlays(); - else - return -1; - } + @Override + public IImageLine readRow() { + // TODO Auto-generated method stub + return super.readRow(); + } - @Override - public IImageLine readRow() { - // TODO Auto-generated method stub - return super.readRow(); - } + @Override + public boolean hasMoreRows() { + // TODO Auto-generated method stub + return super.hasMoreRows(); + } - @Override - public boolean hasMoreRows() { - // TODO Auto-generated method stub - return super.hasMoreRows(); - } + @Override + public IImageLine readRow(final int nrow) { + // TODO Auto-generated method stub + return super.readRow(nrow); + } - @Override - public IImageLine readRow(int nrow) { - // TODO Auto-generated method stub - return super.readRow(nrow); - } + @Override + public IImageLineSet readRows() { + // TODO Auto-generated method stub + return super.readRows(); + } - @Override - public IImageLineSet readRows() { - // TODO Auto-generated method stub - return super.readRows(); - } + @Override + public IImageLineSet readRows(final int nRows, final int rowOffset, final int rowStep) { + // TODO Auto-generated method stub + return super.readRows(nRows, rowOffset, rowStep); + } - @Override - public IImageLineSet readRows(int nRows, int rowOffset, int rowStep) { - // TODO Auto-generated method stub - return super.readRows(nRows, rowOffset, rowStep); - } + @Override + public void readSkippingAllRows() { + // TODO Auto-generated method stub + super.readSkippingAllRows(); + } - @Override - public void readSkippingAllRows() { - // TODO Auto-generated method stub - super.readSkippingAllRows(); - } + @Override + protected ChunkSeqReaderPng createChunkSeqReader() { + final ChunkSeqReaderPng cr = new ChunkSeqReaderPng(false) { - @Override - protected ChunkSeqReaderPng createChunkSeqReader() { - ChunkSeqReaderPng cr = new ChunkSeqReaderPng(false) { + @Override + public boolean shouldSkipContent(final int len, final String id) { + return super.shouldSkipContent(len, id); + } - @Override - public boolean shouldSkipContent(int len, String id) { - return super.shouldSkipContent(len, id); - } + @Override + protected boolean isIdatKind(final String id) { + return id.equals(PngChunkIDAT.ID) || id.equals(PngChunkFDAT.ID); + } - @Override - protected boolean isIdatKind(String id) { - return id.equals(PngChunkIDAT.ID) || id.equals(PngChunkFDAT.ID); - } + @Override + protected DeflatedChunksSet createIdatSet(final String id) { + final IdatSet ids = new IdatSet(id, getCurImgInfo(), deinterlacer); + ids.setCallbackMode(callbackMode); + return ids; + } - @Override - protected DeflatedChunksSet createIdatSet(String id) { - IdatSet ids = new IdatSet(id, getCurImgInfo(), deinterlacer); - ids.setCallbackMode(callbackMode); - return ids; - } + @Override + protected void startNewChunk(final int len, final String id, final long offset) { + super.startNewChunk(len, id, offset); + } + @Override + protected void postProcessChunk(final ChunkReader chunkR) { + super.postProcessChunk(chunkR); + if (chunkR.getChunkRaw().id.equals(PngChunkFCTL.ID)) { + frameNum++; + final List chunkslist = chunkseq.getChunks(); + fctlChunk = (PngChunkFCTL) chunkslist.get(chunkslist.size() - 1); + // as this is slightly dirty, we check + if (chunkR.getChunkRaw().getOffset() != fctlChunk.getRaw().getOffset()) + throw new PngjInputException("something went wrong"); + final ImageInfo frameInfo = fctlChunk.getEquivImageInfo(); + getChunkseq().updateCurImgInfo(frameInfo); + } + } - @Override - protected void startNewChunk(int len, String id, long offset) { - super.startNewChunk(len, id, offset); - } + @SuppressWarnings("unlikely-arg-type") + @Override + protected boolean countChunkTypeAsAncillary(final String id) { + // we don't count fdat as ancillary data + return super.countChunkTypeAsAncillary(id) && !id.equals(id.equals(PngChunkFDAT.ID)); + } - @Override - protected void postProcessChunk(ChunkReader chunkR) { - super.postProcessChunk(chunkR); - if (chunkR.getChunkRaw().id.equals(PngChunkFCTL.ID)) { - frameNum++; - List chunkslist = chunkseq.getChunks(); - fctlChunk = (PngChunkFCTL) chunkslist.get(chunkslist.size() - 1); - // as this is slightly dirty, we check - if (chunkR.getChunkRaw().getOffset() != fctlChunk.getRaw().getOffset()) - throw new PngjInputException("something went wrong"); - ImageInfo frameInfo = fctlChunk.getEquivImageInfo(); - getChunkseq().updateCurImgInfo(frameInfo); - } - } + }; + return cr; + } - @Override - protected boolean countChunkTypeAsAncillary(String id) { - // we don't count fdat as ancillary data - return super.countChunkTypeAsAncillary(id) && !id.equals(id.equals(PngChunkFDAT.ID)); - } - - }; - return cr; - } - - /** - * @see #frameNum - */ - public int getFrameNum() { - return frameNum; - } - - @Override - public void end() { - // TODO Auto-generated method stub - super.end(); - } - - public PngChunkFCTL getFctl() { - return fctlChunk; - } + /** + * @see #frameNum + */ + public int getFrameNum() { + return frameNum; + } + @Override + public void end() { + // TODO Auto-generated method stub + super.end(); + } + public PngChunkFCTL getFctl() { + return fctlChunk; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/PngReaderByte.java b/teavm/src/main/java/ar/com/hjg/pngj/PngReaderByte.java index 3b34fdf6..08307047 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/PngReaderByte.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/PngReaderByte.java @@ -6,25 +6,27 @@ import java.io.InputStream; /** * Trivial extension of {@link PngReader} that uses {@link ImageLineByte} *

- * The factory is set at construction time. Remember that this could still be changed at runtime. + * The factory is set at construction time. Remember that this could still be + * changed at runtime. */ public class PngReaderByte extends PngReader { - public PngReaderByte(File file) { - super(file); - setLineSetFactory(ImageLineSetDefault.getFactoryByte()); - } + public PngReaderByte(final File file) { + super(file); + setLineSetFactory(ImageLineSetDefault.getFactoryByte()); + } - public PngReaderByte(InputStream inputStream) { - super(inputStream); - setLineSetFactory(ImageLineSetDefault.getFactoryByte()); - } + public PngReaderByte(final InputStream inputStream) { + super(inputStream); + setLineSetFactory(ImageLineSetDefault.getFactoryByte()); + } - /** - * Utility method that casts {@link #readRow()} return to {@link ImageLineByte}. - */ - public ImageLineByte readRowByte() { - return (ImageLineByte) readRow(); - } + /** + * Utility method that casts {@link #readRow()} return to + * {@link ImageLineByte}. + */ + public ImageLineByte readRowByte() { + return (ImageLineByte) readRow(); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/PngReaderFilter.java b/teavm/src/main/java/ar/com/hjg/pngj/PngReaderFilter.java index cafe2d4c..b2341561 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/PngReaderFilter.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/PngReaderFilter.java @@ -8,92 +8,94 @@ import java.util.List; import ar.com.hjg.pngj.chunks.PngChunk; /** - * This class allows to use a simple PNG reader as an input filter, wrapping a ChunkSeqReaderPng in callback mode. - * - * In this sample implementation, all IDAT chunks are skipped and the rest are stored. An example of use, that lets us + * This class allows to use a simple PNG reader as an input filter, wrapping a + * ChunkSeqReaderPng in callback mode. + * + * In this sample implementation, all IDAT chunks are skipped and the rest are + * stored. An example of use, that lets us * grab the Metadata and let the pixels go towards a BufferedImage: - * - * + * + * *

  * PngReaderFilter reader = new PngReaderFilter(new FileInputStream("image.png"));
  * BufferedImage image1 = ImageIO.read(reader);
  * reader.readUntilEndAndClose(); // in case ImageIO.read() does not read the traling chunks (it happens)
  * System.out.println(reader.getChunksList());
  * 
- * + * */ public class PngReaderFilter extends FilterInputStream { - private ChunkSeqReaderPng chunkseq; + private final ChunkSeqReaderPng chunkseq; - public PngReaderFilter(InputStream arg0) { - super(arg0); - chunkseq = createChunkSequenceReader(); - } + public PngReaderFilter(final InputStream arg0) { + super(arg0); + chunkseq = createChunkSequenceReader(); + } - protected ChunkSeqReaderPng createChunkSequenceReader() { - return new ChunkSeqReaderPng(true) { - @Override - public boolean shouldSkipContent(int len, String id) { - return super.shouldSkipContent(len, id) || id.equals("IDAT"); - } + protected ChunkSeqReaderPng createChunkSequenceReader() { + return new ChunkSeqReaderPng(true) { + @Override + public boolean shouldSkipContent(final int len, final String id) { + return super.shouldSkipContent(len, id) || id.equals("IDAT"); + } - @Override - protected boolean shouldCheckCrc(int len, String id) { - return false; - } + @Override + protected boolean shouldCheckCrc(final int len, final String id) { + return false; + } - @Override - protected void postProcessChunk(ChunkReader chunkR) { - super.postProcessChunk(chunkR); - // System.out.println("processed chunk " + chunkR.getChunkRaw().id); - } - }; - } + @Override + protected void postProcessChunk(final ChunkReader chunkR) { + super.postProcessChunk(chunkR); + // System.out.println("processed chunk " + chunkR.getChunkRaw().id); + } + }; + } - @Override - public void close() throws IOException { - super.close(); - chunkseq.close(); - } + @Override + public void close() throws IOException { + super.close(); + chunkseq.close(); + } - @Override - public int read() throws IOException { - int r = super.read(); - if (r > 0) - chunkseq.feedAll(new byte[] {(byte) r}, 0, 1); - return r; - } + @Override + public int read() throws IOException { + final int r = super.read(); + if (r > 0) + chunkseq.feedAll(new byte[] { (byte) r }, 0, 1); + return r; + } - @Override - public int read(byte[] b, int off, int len) throws IOException { - int res = super.read(b, off, len); - if (res > 0) - chunkseq.feedAll(b, off, res); - return res; - } + @Override + public int read(final byte[] b, final int off, final int len) throws IOException { + final int res = super.read(b, off, len); + if (res > 0) + chunkseq.feedAll(b, off, res); + return res; + } - @Override - public int read(byte[] b) throws IOException { - int res = super.read(b); - if (res > 0) - chunkseq.feedAll(b, 0, res); - return res; - } + @Override + public int read(final byte[] b) throws IOException { + final int res = super.read(b); + if (res > 0) + chunkseq.feedAll(b, 0, res); + return res; + } - public void readUntilEndAndClose() throws IOException { - BufferedStreamFeeder br = new BufferedStreamFeeder(this.in); - while ((!chunkseq.isDone()) && br.hasMoreToFeed()) - br.feed(chunkseq); - close(); - } + public void readUntilEndAndClose() throws IOException { + final BufferedStreamFeeder br = new BufferedStreamFeeder(in); + while (!chunkseq.isDone() && br.hasMoreToFeed()) + br.feed(chunkseq); + close(); + } - public List getChunksList() { - return chunkseq.getChunks(); - } + public List getChunksList() { + return chunkseq.getChunks(); + } - public ChunkSeqReaderPng getChunkseq() { - return chunkseq; - } + public ChunkSeqReaderPng getChunkseq() { + return chunkseq; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/PngReaderInt.java b/teavm/src/main/java/ar/com/hjg/pngj/PngReaderInt.java index 9f18cfb6..aef62bc5 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/PngReaderInt.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/PngReaderInt.java @@ -6,32 +6,34 @@ import java.io.InputStream; /** * Trivial extension of {@link PngReader} that uses {@link ImageLineInt}. *

- * In the current implementation this is quite dummy/redundant, because (for backward compatibility) PngReader already + * In the current implementation this is quite dummy/redundant, because (for + * backward compatibility) PngReader already * uses a {@link ImageLineInt}. *

- * The factory is set at construction time. Remember that this could still be changed at runtime. + * The factory is set at construction time. Remember that this could still be + * changed at runtime. */ public class PngReaderInt extends PngReader { - public PngReaderInt(File file) { - super(file); // not necessary to set factory, PngReader already does that - } + public PngReaderInt(final File file) { + super(file); // not necessary to set factory, PngReader already does that + } - public PngReaderInt(InputStream inputStream) { - super(inputStream); - } + public PngReaderInt(final InputStream inputStream) { + super(inputStream); + } - /** - * Utility method that casts the IImageLine to a ImageLineInt - * - * This only make sense for this concrete class - * - */ - public ImageLineInt readRowInt() { - IImageLine line = readRow(); - if (line instanceof ImageLineInt) - return (ImageLineInt) line; - else - throw new PngjException("This is not a ImageLineInt : " + line.getClass()); - } + /** + * Utility method that casts the IImageLine to a ImageLineInt + * + * This only make sense for this concrete class + * + */ + public ImageLineInt readRowInt() { + final IImageLine line = readRow(); + if (line instanceof ImageLineInt) + return (ImageLineInt) line; + else + throw new PngjException("This is not a ImageLineInt : " + line.getClass()); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/PngWriter.java b/teavm/src/main/java/ar/com/hjg/pngj/PngWriter.java index c8906906..2be57f39 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/PngWriter.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/PngWriter.java @@ -21,407 +21,433 @@ import ar.com.hjg.pngj.pixels.PixelsWriterDefault; */ public class PngWriter { - public final ImageInfo imgInfo; + public final ImageInfo imgInfo; - /** - * last writen row number, starting from 0 - */ - protected int rowNum = -1; - - private final ChunksListForWrite chunksList; - - private final PngMetadata metadata; - - /** - * Current chunk grounp, (0-6) already written or currently writing (this is advanced when just starting to write the - * new group, not when finalizing the previous) - *

- * see {@link ChunksList} - */ - protected int currentChunkGroup = -1; - - private int passes = 1; // Some writes might require two passes (NOT USED STILL) - private int currentpass = 0; // numbered from 1 - - private boolean shouldCloseStream = true; - - private int idatMaxSize = 0; // 0=use default (PngIDatChunkOutputStream 64k) - // private PngIDatChunkOutputStream datStream; - - protected PixelsWriter pixelsWriter; - - private final OutputStream os; - - private ChunkPredicate copyFromPredicate = null; - private ChunksList copyFromList = null; - - protected StringBuilder debuginfo = new StringBuilder(); - - /** - * Opens a file for writing. - *

- * Sets shouldCloseStream=true. For more info see {@link #PngWriter(OutputStream, ImageInfo)} - * - * @param file - * @param imgInfo - * @param allowoverwrite If false and file exists, an {@link PngjOutputException} is thrown - */ - public PngWriter(File file, ImageInfo imgInfo, boolean allowoverwrite) { - this(PngHelperInternal.ostreamFromFile(file, allowoverwrite), imgInfo); - setShouldCloseStream(true); - } - - /** - * @see #PngWriter(File, ImageInfo, boolean) (overwrite=true) - */ - public PngWriter(File file, ImageInfo imgInfo) { - this(file, imgInfo, true); - } - - /** - * Constructs a new PngWriter from a output stream. After construction nothing is writen yet. You still can set some - * parameters (compression, filters) and queue chunks before start writing the pixels. - *

- * - * @param outputStream Open stream for binary writing - * @param imgInfo Basic image parameters - */ - public PngWriter(OutputStream outputStream, ImageInfo imgInfo) { - this.os = outputStream; - this.imgInfo = imgInfo; - // prealloc - chunksList = new ChunksListForWrite(imgInfo); - metadata = new PngMetadata(chunksList); - pixelsWriter = createPixelsWriter(imgInfo); - setCompLevel(9); - } - - private void initIdat() { // this triggers the writing of first chunks - pixelsWriter.setOs(this.os); - pixelsWriter.setIdatMaxSize(idatMaxSize); - writeSignatureAndIHDR(); - writeFirstChunks(); - } - - private void writeEndChunk() { - currentChunkGroup = ChunksList.CHUNK_GROUP_6_END; - PngChunkIEND c = new PngChunkIEND(imgInfo); - c.createRawChunk().writeChunk(os); - chunksList.getChunks().add(c); - } - - private void writeFirstChunks() { - if (currentChunkGroup >= ChunksList.CHUNK_GROUP_4_IDAT) - return; - int nw = 0; - currentChunkGroup = ChunksList.CHUNK_GROUP_1_AFTERIDHR; - queueChunksFromOther(); - nw = chunksList.writeChunks(os, currentChunkGroup); - currentChunkGroup = ChunksList.CHUNK_GROUP_2_PLTE; - nw = chunksList.writeChunks(os, currentChunkGroup); - if (nw > 0 && imgInfo.greyscale) - throw new PngjOutputException("cannot write palette for this format"); - if (nw == 0 && imgInfo.indexed) - throw new PngjOutputException("missing palette"); - currentChunkGroup = ChunksList.CHUNK_GROUP_3_AFTERPLTE; - nw = chunksList.writeChunks(os, currentChunkGroup); - } - - private void writeLastChunks() { // not including end - currentChunkGroup = ChunksList.CHUNK_GROUP_5_AFTERIDAT; - queueChunksFromOther(); - chunksList.writeChunks(os, currentChunkGroup); - // should not be unwriten chunks - List pending = chunksList.getQueuedChunks(); - if (!pending.isEmpty()) - throw new PngjOutputException(pending.size() + " chunks were not written! Eg: " - + pending.get(0).toString()); - } - - /** - * Write id signature and also "IHDR" chunk - */ - private void writeSignatureAndIHDR() { - PngHelperInternal.writeBytes(os, PngHelperInternal.getPngIdSignature()); // signature - currentChunkGroup = ChunksList.CHUNK_GROUP_0_IDHR; - PngChunkIHDR ihdr = new PngChunkIHDR(imgInfo); - // http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html - ihdr.createRawChunk().writeChunk(os); - chunksList.getChunks().add(ihdr); - } - - private void queueChunksFromOther() { - if (copyFromList == null || copyFromPredicate == null) - return; - boolean idatDone = currentChunkGroup >= ChunksList.CHUNK_GROUP_4_IDAT; // we assume this method is not either before - // or after the IDAT writing, not in the - // middle! - for (PngChunk chunk : copyFromList.getChunks()) { - if (chunk.getRaw().data == null) - continue; // we cannot copy skipped chunks? - int groupOri = chunk.getChunkGroup(); - if (groupOri <= ChunksList.CHUNK_GROUP_4_IDAT && idatDone) - continue; - if (groupOri >= ChunksList.CHUNK_GROUP_4_IDAT && !idatDone) - continue; - if (chunk.crit && !chunk.id.equals(PngChunkPLTE.ID)) - continue; // critical chunks (except perhaps PLTE) are never - // copied - boolean copy = copyFromPredicate.match(chunk); - if (copy) { - // but if the chunk is already queued or writen, it's ommited! - if (chunksList.getEquivalent(chunk).isEmpty() - && chunksList.getQueuedEquivalent(chunk).isEmpty()) { - chunksList.queue(chunk); - } - } - } - } - -/** - * Queues an ancillary chunk for writing. - *

- * If a "equivalent" chunk is already queued (see {@link ChunkHelper#equivalent(PngChunk, PngChunk)), this overwrites it. - *

- * The chunk will be written as late as possible, unless the priority is set. - * - * @param chunk - */ - public void queueChunk(PngChunk chunk) { - for (PngChunk other : chunksList.getQueuedEquivalent(chunk)) { - getChunksList().removeChunk(other); - } - chunksList.queue(chunk); - } - - /** - * Sets an origin (typically from a {@link PngReader}) of Chunks to be copied. This should be called only once, before - * starting writing the rows. It doesn't matter the current state of the PngReader reading, this is a live object and - * what matters is that when the writer writes the pixels (IDAT) the reader has already read them, and that when the - * writer ends, the reader is already ended (all this is very natural). - *

- * Apart from the copyMask, there is some addional heuristics: - *

- * - The chunks will be queued, but will be written as late as possible (unless you explicitly set priority=true) - *

- * - The chunk will not be queued if an "equivalent" chunk was already queued explicitly. And it will be overwriten - * another is queued explicitly. - * - * @param chunks - * @param copyMask Some bitmask from {@link ChunkCopyBehaviour} - * - * @see #copyChunksFrom(ChunksList, ChunkPredicate) - */ - public void copyChunksFrom(ChunksList chunks, int copyMask) { - copyChunksFrom(chunks, ChunkCopyBehaviour.createPredicate(copyMask, imgInfo)); - } - - /** - * Copy all chunks from origin. See {@link #copyChunksFrom(ChunksList, int)} for more info - */ - public void copyChunksFrom(ChunksList chunks) { - copyChunksFrom(chunks, ChunkCopyBehaviour.COPY_ALL); - } - - /** - * Copy chunks from origin depending on some {@link ChunkPredicate} - * - * @param chunks - * @param predicate The chunks (ancillary or PLTE) will be copied if and only if predicate matches - * - * @see #copyChunksFrom(ChunksList, int) for more info - */ - public void copyChunksFrom(ChunksList chunks, ChunkPredicate predicate) { - if (copyFromList != null && chunks != null) - PngHelperInternal.LOGGER.warning("copyChunksFrom should only be called once"); - if (predicate == null) - throw new PngjOutputException("copyChunksFrom requires a predicate"); - this.copyFromList = chunks; - this.copyFromPredicate = predicate; - } - - /** - * Computes compressed size/raw size, approximate. - *

- * Actually: compressed size = total size of IDAT data , raw size = uncompressed pixel bytes = rows * (bytesPerRow + - * 1). - * - * This must be called after pngw.end() - */ - public double computeCompressionRatio() { - if (currentChunkGroup < ChunksList.CHUNK_GROUP_5_AFTERIDAT) - throw new PngjOutputException("must be called after end()"); - return pixelsWriter.getCompression(); - } - - /** - * Finalizes all the steps and closes the stream. This must be called after writing the lines. Idempotent - */ - public void end() { - if (rowNum != imgInfo.rows - 1 || !pixelsWriter.isDone()) - throw new PngjOutputException("all rows have not been written"); - try { - if (pixelsWriter != null) - pixelsWriter.close(); - if (currentChunkGroup < ChunksList.CHUNK_GROUP_5_AFTERIDAT) - writeLastChunks(); - if (currentChunkGroup < ChunksList.CHUNK_GROUP_6_END) - writeEndChunk(); - } finally { - close(); - } - } - - /** - * Closes and releases resources - *

- * This is normally called internally from {@link #end()}, you should only call this for aborting the writing and - * release resources (close the stream). - *

- * Idempotent and secure - never throws exceptions - */ - public void close() { - if (pixelsWriter != null) - pixelsWriter.close(); - if (shouldCloseStream && os != null) - try { - os.close(); - } catch (Exception e) { - PngHelperInternal.LOGGER.warning("Error closing writer " + e.toString()); - } - } - - /** - * returns the chunks list (queued and writen chunks) - */ - public ChunksListForWrite getChunksList() { - return chunksList; - } - - /** - * Retruns a high level wrapper over for metadata handling - */ - public PngMetadata getMetadata() { - return metadata; - } - - /** - * Sets internal prediction filter type, or strategy to choose it. - *

- * This must be called just after constructor, before starting writing. - *

- */ - public void setFilterType(FilterType filterType) { - pixelsWriter.setFilterType(filterType); - } - - /** - * This is kept for backwards compatibility, now the PixelsWriter object should be used for setting - * compression/filtering options - * - * @see PixelsWriter#setCompressionFactor(double) - * @param compLevel between 0 (no compression, max speed) and 9 (max compression) - */ - public void setCompLevel(int complevel) { - pixelsWriter.setDeflaterCompLevel(complevel); - } - - /** - * + /** + * last writen row number, starting from 0 */ - public void setFilterPreserve(boolean filterPreserve) { - if (filterPreserve) - pixelsWriter.setFilterType(FilterType.FILTER_PRESERVE); - else if (pixelsWriter.getFilterType() == null) - pixelsWriter.setFilterType(FilterType.FILTER_DEFAULT); - } + protected int rowNum = -1; - /** - * Sets maximum size of IDAT fragments. Incrementing this from the default has very little effect on compression and - * increments memory usage. You should rarely change this. - *

- * - * @param idatMaxSize default=0 : use defaultSize (32K) - */ - public void setIdatMaxSize(int idatMaxSize) { - this.idatMaxSize = idatMaxSize; - } + private final ChunksListForWrite chunksList; - /** - * If true, output stream will be closed after ending write - *

- * default=true - */ - public void setShouldCloseStream(boolean shouldCloseStream) { - this.shouldCloseStream = shouldCloseStream; - } + private final PngMetadata metadata; - /** - * Writes next row, does not check row number. - * - * @param imgline - */ - public void writeRow(IImageLine imgline) { - writeRow(imgline, rowNum + 1); - } + /** + * Current chunk grounp, (0-6) already written or currently writing (this is + * advanced when just starting to write the + * new group, not when finalizing the previous) + *

+ * see {@link ChunksList} + */ + protected int currentChunkGroup = -1; - /** - * Writes the full set of row. The ImageLineSet should contain (allow to acces) imgInfo.rows - */ - public void writeRows(IImageLineSet imglines) { - for (int i = 0; i < imgInfo.rows; i++) - writeRow(imglines.getImageLineRawNum(i)); - } + private final int passes = 1; // Some writes might require two passes (NOT USED STILL) + private int currentpass = 0; // numbered from 1 - public void writeRow(IImageLine imgline, int rownumber) { - rowNum++; - if (rowNum == imgInfo.rows) - rowNum = 0; - if (rownumber == imgInfo.rows) - rownumber = 0; - if (rownumber >= 0 && rowNum != rownumber) - throw new PngjOutputException("rows must be written in order: expected:" + rowNum - + " passed:" + rownumber); - if (rowNum == 0) - currentpass++; - if (rownumber == 0 && currentpass == passes) { - initIdat(); - currentChunkGroup = ChunksList.CHUNK_GROUP_4_IDAT; // we just begin writing IDAT - } - byte[] rowb = pixelsWriter.getRowb(); - imgline.writeToPngRaw(rowb); - pixelsWriter.processRow(rowb); + private boolean shouldCloseStream = true; - } + private int idatMaxSize = 0; // 0=use default (PngIDatChunkOutputStream 64k) + // private PngIDatChunkOutputStream datStream; - /** - * Utility method, uses internaly a ImageLineInt - */ - public void writeRowInt(int[] buf) { - writeRow(new ImageLineInt(imgInfo, buf)); - } + protected PixelsWriter pixelsWriter; - /** - * Factory method for pixels writer. This will be called once at the moment at start writing a set of IDAT chunks - * (typically once in a normal PNG) - * - * This should be overriden if custom filtering strategies are desired. Remember to release this with close() - * - * @param imginfo Might be different than that of this object (eg: APNG with subimages) - * @param os Output stream - * @return new PixelsWriter. Don't forget to call close() when discarding it - */ - protected PixelsWriter createPixelsWriter(ImageInfo imginfo) { - PixelsWriterDefault pw = new PixelsWriterDefault(imginfo); - return pw; - } + private final OutputStream os; - public final PixelsWriter getPixelsWriter() { - return pixelsWriter; - } + private ChunkPredicate copyFromPredicate = null; + private ChunksList copyFromList = null; - public String getDebuginfo() { - return debuginfo.toString(); - } + protected StringBuilder debuginfo = new StringBuilder(); + + /** + * Opens a file for writing. + *

+ * Sets shouldCloseStream=true. For more info see + * {@link #PngWriter(OutputStream, ImageInfo)} + * + * @param file + * @param imgInfo + * @param allowoverwrite + * If false and file exists, an {@link PngjOutputException} is + * thrown + */ + public PngWriter(final File file, final ImageInfo imgInfo, final boolean allowoverwrite) { + this(PngHelperInternal.ostreamFromFile(file, allowoverwrite), imgInfo); + setShouldCloseStream(true); + } + + /** + * @see #PngWriter(File, ImageInfo, boolean) (overwrite=true) + */ + public PngWriter(final File file, final ImageInfo imgInfo) { + this(file, imgInfo, true); + } + + /** + * Constructs a new PngWriter from a output stream. After construction + * nothing is writen yet. You still can set some + * parameters (compression, filters) and queue chunks before start writing + * the pixels. + *

+ * + * @param outputStream + * Open stream for binary writing + * @param imgInfo + * Basic image parameters + */ + public PngWriter(final OutputStream outputStream, final ImageInfo imgInfo) { + os = outputStream; + this.imgInfo = imgInfo; + // prealloc + chunksList = new ChunksListForWrite(imgInfo); + metadata = new PngMetadata(chunksList); + pixelsWriter = createPixelsWriter(imgInfo); + setCompLevel(9); + } + + private void initIdat() { // this triggers the writing of first chunks + pixelsWriter.setOs(os); + pixelsWriter.setIdatMaxSize(idatMaxSize); + writeSignatureAndIHDR(); + writeFirstChunks(); + } + + private void writeEndChunk() { + currentChunkGroup = ChunksList.CHUNK_GROUP_6_END; + final PngChunkIEND c = new PngChunkIEND(imgInfo); + c.createRawChunk().writeChunk(os); + chunksList.getChunks().add(c); + } + + private void writeFirstChunks() { + if (currentChunkGroup >= ChunksList.CHUNK_GROUP_4_IDAT) + return; + int nw = 0; + currentChunkGroup = ChunksList.CHUNK_GROUP_1_AFTERIDHR; + queueChunksFromOther(); + nw = chunksList.writeChunks(os, currentChunkGroup); + currentChunkGroup = ChunksList.CHUNK_GROUP_2_PLTE; + nw = chunksList.writeChunks(os, currentChunkGroup); + if (nw > 0 && imgInfo.greyscale) + throw new PngjOutputException("cannot write palette for this format"); + if (nw == 0 && imgInfo.indexed) + throw new PngjOutputException("missing palette"); + currentChunkGroup = ChunksList.CHUNK_GROUP_3_AFTERPLTE; + nw = chunksList.writeChunks(os, currentChunkGroup); + } + + private void writeLastChunks() { // not including end + currentChunkGroup = ChunksList.CHUNK_GROUP_5_AFTERIDAT; + queueChunksFromOther(); + chunksList.writeChunks(os, currentChunkGroup); + // should not be unwriten chunks + final List pending = chunksList.getQueuedChunks(); + if (!pending.isEmpty()) + throw new PngjOutputException(pending.size() + " chunks were not written! Eg: " + pending.get(0).toString()); + } + + /** + * Write id signature and also "IHDR" chunk + */ + private void writeSignatureAndIHDR() { + PngHelperInternal.writeBytes(os, PngHelperInternal.getPngIdSignature()); // signature + currentChunkGroup = ChunksList.CHUNK_GROUP_0_IDHR; + final PngChunkIHDR ihdr = new PngChunkIHDR(imgInfo); + // http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html + ihdr.createRawChunk().writeChunk(os); + chunksList.getChunks().add(ihdr); + } + + private void queueChunksFromOther() { + if (copyFromList == null || copyFromPredicate == null) + return; + final boolean idatDone = currentChunkGroup >= ChunksList.CHUNK_GROUP_4_IDAT; // we assume this method is not either before + // or after the IDAT writing, not in the + // middle! + for (final PngChunk chunk : copyFromList.getChunks()) { + if (chunk.getRaw().data == null) + continue; // we cannot copy skipped chunks? + final int groupOri = chunk.getChunkGroup(); + if (groupOri <= ChunksList.CHUNK_GROUP_4_IDAT && idatDone) + continue; + if (groupOri >= ChunksList.CHUNK_GROUP_4_IDAT && !idatDone) + continue; + if (chunk.crit && !chunk.id.equals(PngChunkPLTE.ID)) + continue; // critical chunks (except perhaps PLTE) are never + // copied + final boolean copy = copyFromPredicate.match(chunk); + if (copy) + // but if the chunk is already queued or writen, it's ommited! + if (chunksList.getEquivalent(chunk).isEmpty() && chunksList.getQueuedEquivalent(chunk).isEmpty()) + chunksList.queue(chunk); + } + } + + /** + * Queues an ancillary chunk for writing. + *

+ * If a "equivalent" chunk is already queued (see + * {@link ChunkHelper#equivalent(PngChunk, PngChunk)), this overwrites it. + *

+ * The chunk will be written as late as possible, unless the priority is + * set. + * + * @param chunk + */ + public void queueChunk(final PngChunk chunk) { + for (final PngChunk other : chunksList.getQueuedEquivalent(chunk)) + getChunksList().removeChunk(other); + chunksList.queue(chunk); + } + + /** + * Sets an origin (typically from a {@link PngReader}) of Chunks to be + * copied. This should be called only once, before + * starting writing the rows. It doesn't matter the current state of the + * PngReader reading, this is a live object and + * what matters is that when the writer writes the pixels (IDAT) the reader + * has already read them, and that when the + * writer ends, the reader is already ended (all this is very natural). + *

+ * Apart from the copyMask, there is some addional heuristics: + *

+ * - The chunks will be queued, but will be written as late as possible + * (unless you explicitly set priority=true) + *

+ * - The chunk will not be queued if an "equivalent" chunk was already + * queued explicitly. And it will be overwriten + * another is queued explicitly. + * + * @param chunks + * @param copyMask + * Some bitmask from {@link ChunkCopyBehaviour} + * + * @see #copyChunksFrom(ChunksList, ChunkPredicate) + */ + public void copyChunksFrom(final ChunksList chunks, final int copyMask) { + copyChunksFrom(chunks, ChunkCopyBehaviour.createPredicate(copyMask, imgInfo)); + } + + /** + * Copy all chunks from origin. See {@link #copyChunksFrom(ChunksList, int)} + * for more info + */ + public void copyChunksFrom(final ChunksList chunks) { + copyChunksFrom(chunks, ChunkCopyBehaviour.COPY_ALL); + } + + /** + * Copy chunks from origin depending on some {@link ChunkPredicate} + * + * @param chunks + * @param predicate + * The chunks (ancillary or PLTE) will be copied if and only if + * predicate matches + * + * @see #copyChunksFrom(ChunksList, int) for more info + */ + public void copyChunksFrom(final ChunksList chunks, final ChunkPredicate predicate) { + if (copyFromList != null && chunks != null) + PngHelperInternal.LOGGER.warning("copyChunksFrom should only be called once"); + if (predicate == null) + throw new PngjOutputException("copyChunksFrom requires a predicate"); + copyFromList = chunks; + copyFromPredicate = predicate; + } + + /** + * Computes compressed size/raw size, approximate. + *

+ * Actually: compressed size = total size of IDAT data , raw size = + * uncompressed pixel bytes = rows * (bytesPerRow + + * 1). + * + * This must be called after pngw.end() + */ + public double computeCompressionRatio() { + if (currentChunkGroup < ChunksList.CHUNK_GROUP_5_AFTERIDAT) + throw new PngjOutputException("must be called after end()"); + return pixelsWriter.getCompression(); + } + + /** + * Finalizes all the steps and closes the stream. This must be called after + * writing the lines. Idempotent + */ + public void end() { + if (rowNum != imgInfo.rows - 1 || !pixelsWriter.isDone()) + throw new PngjOutputException("all rows have not been written"); + try { + if (pixelsWriter != null) + pixelsWriter.close(); + if (currentChunkGroup < ChunksList.CHUNK_GROUP_5_AFTERIDAT) + writeLastChunks(); + if (currentChunkGroup < ChunksList.CHUNK_GROUP_6_END) + writeEndChunk(); + } finally { + close(); + } + } + + /** + * Closes and releases resources + *

+ * This is normally called internally from {@link #end()}, you should only + * call this for aborting the writing and + * release resources (close the stream). + *

+ * Idempotent and secure - never throws exceptions + */ + public void close() { + if (pixelsWriter != null) + pixelsWriter.close(); + if (shouldCloseStream && os != null) + try { + os.close(); + } catch (final Exception e) { + PngHelperInternal.LOGGER.warning("Error closing writer " + e.toString()); + } + } + + /** + * returns the chunks list (queued and writen chunks) + */ + public ChunksListForWrite getChunksList() { + return chunksList; + } + + /** + * Retruns a high level wrapper over for metadata handling + */ + public PngMetadata getMetadata() { + return metadata; + } + + /** + * Sets internal prediction filter type, or strategy to choose it. + *

+ * This must be called just after constructor, before starting writing. + *

+ */ + public void setFilterType(final FilterType filterType) { + pixelsWriter.setFilterType(filterType); + } + + /** + * This is kept for backwards compatibility, now the PixelsWriter object + * should be used for setting + * compression/filtering options + * + * @see PixelsWriter#setCompressionFactor(double) + * @param compLevel + * between 0 (no compression, max speed) and 9 (max compression) + */ + public void setCompLevel(final int complevel) { + pixelsWriter.setDeflaterCompLevel(complevel); + } + + /** + * + */ + public void setFilterPreserve(final boolean filterPreserve) { + if (filterPreserve) + pixelsWriter.setFilterType(FilterType.FILTER_PRESERVE); + else if (pixelsWriter.getFilterType() == null) + pixelsWriter.setFilterType(FilterType.FILTER_DEFAULT); + } + + /** + * Sets maximum size of IDAT fragments. Incrementing this from the default + * has very little effect on compression and + * increments memory usage. You should rarely change this. + *

+ * + * @param idatMaxSize + * default=0 : use defaultSize (32K) + */ + public void setIdatMaxSize(final int idatMaxSize) { + this.idatMaxSize = idatMaxSize; + } + + /** + * If true, output stream will be closed after ending write + *

+ * default=true + */ + public void setShouldCloseStream(final boolean shouldCloseStream) { + this.shouldCloseStream = shouldCloseStream; + } + + /** + * Writes next row, does not check row number. + * + * @param imgline + */ + public void writeRow(final IImageLine imgline) { + writeRow(imgline, rowNum + 1); + } + + /** + * Writes the full set of row. The ImageLineSet should contain (allow to + * acces) imgInfo.rows + */ + public void writeRows(final IImageLineSet imglines) { + for (int i = 0; i < imgInfo.rows; i++) + writeRow(imglines.getImageLineRawNum(i)); + } + + public void writeRow(final IImageLine imgline, int rownumber) { + rowNum++; + if (rowNum == imgInfo.rows) + rowNum = 0; + if (rownumber == imgInfo.rows) + rownumber = 0; + if (rownumber >= 0 && rowNum != rownumber) + throw new PngjOutputException("rows must be written in order: expected:" + rowNum + " passed:" + rownumber); + if (rowNum == 0) + currentpass++; + if (rownumber == 0 && currentpass == passes) { + initIdat(); + currentChunkGroup = ChunksList.CHUNK_GROUP_4_IDAT; // we just begin writing IDAT + } + final byte[] rowb = pixelsWriter.getRowb(); + imgline.writeToPngRaw(rowb); + pixelsWriter.processRow(rowb); + + } + + /** + * Utility method, uses internaly a ImageLineInt + */ + public void writeRowInt(final int[] buf) { + writeRow(new ImageLineInt(imgInfo, buf)); + } + + /** + * Factory method for pixels writer. This will be called once at the moment + * at start writing a set of IDAT chunks + * (typically once in a normal PNG) + * + * This should be overriden if custom filtering strategies are desired. + * Remember to release this with close() + * + * @param imginfo + * Might be different than that of this object (eg: APNG with + * subimages) + * @param os + * Output stream + * @return new PixelsWriter. Don't forget to call close() when discarding it + */ + protected PixelsWriter createPixelsWriter(final ImageInfo imginfo) { + final PixelsWriterDefault pw = new PixelsWriterDefault(imginfo); + return pw; + } + + public final PixelsWriter getPixelsWriter() { + return pixelsWriter; + } + + public String getDebuginfo() { + return debuginfo.toString(); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/PngWriterHc.java b/teavm/src/main/java/ar/com/hjg/pngj/PngWriterHc.java index cc83df84..aec2140c 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/PngWriterHc.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/PngWriterHc.java @@ -9,27 +9,27 @@ import ar.com.hjg.pngj.pixels.PixelsWriterMultiple; /** Pngwriter with High compression EXPERIMENTAL */ public class PngWriterHc extends PngWriter { - public PngWriterHc(File file, ImageInfo imgInfo, boolean allowoverwrite) { - super(file, imgInfo, allowoverwrite); - setFilterType(FilterType.FILTER_SUPER_ADAPTIVE); - } + public PngWriterHc(final File file, final ImageInfo imgInfo, final boolean allowoverwrite) { + super(file, imgInfo, allowoverwrite); + setFilterType(FilterType.FILTER_SUPER_ADAPTIVE); + } - public PngWriterHc(File file, ImageInfo imgInfo) { - super(file, imgInfo); - } + public PngWriterHc(final File file, final ImageInfo imgInfo) { + super(file, imgInfo); + } - public PngWriterHc(OutputStream outputStream, ImageInfo imgInfo) { - super(outputStream, imgInfo); - } + public PngWriterHc(final OutputStream outputStream, final ImageInfo imgInfo) { + super(outputStream, imgInfo); + } - @Override - protected PixelsWriter createPixelsWriter(ImageInfo imginfo) { - PixelsWriterMultiple pw = new PixelsWriterMultiple(imginfo); - return pw; - } + @Override + protected PixelsWriter createPixelsWriter(final ImageInfo imginfo) { + final PixelsWriterMultiple pw = new PixelsWriterMultiple(imginfo); + return pw; + } - public PixelsWriterMultiple getPixelWriterMultiple() { - return (PixelsWriterMultiple) pixelsWriter; - } + public PixelsWriterMultiple getPixelWriterMultiple() { + return (PixelsWriterMultiple) pixelsWriter; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/PngjBadCrcException.java b/teavm/src/main/java/ar/com/hjg/pngj/PngjBadCrcException.java index 8e337a0c..1efbada2 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/PngjBadCrcException.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/PngjBadCrcException.java @@ -4,17 +4,17 @@ package ar.com.hjg.pngj; * Exception thrown by bad CRC check */ public class PngjBadCrcException extends PngjInputException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public PngjBadCrcException(String message, Throwable cause) { - super(message, cause); - } + public PngjBadCrcException(final String message, final Throwable cause) { + super(message, cause); + } - public PngjBadCrcException(String message) { - super(message); - } + public PngjBadCrcException(final String message) { + super(message); + } - public PngjBadCrcException(Throwable cause) { - super(cause); - } + public PngjBadCrcException(final Throwable cause) { + super(cause); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/PngjException.java b/teavm/src/main/java/ar/com/hjg/pngj/PngjException.java index 8471c70a..f99f1df5 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/PngjException.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/PngjException.java @@ -4,17 +4,17 @@ package ar.com.hjg.pngj; * Generic exception for this library. It's a RuntimeException (unchecked) */ public class PngjException extends RuntimeException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public PngjException(String message, Throwable cause) { - super(message, cause); - } + public PngjException(final String message, final Throwable cause) { + super(message, cause); + } - public PngjException(String message) { - super(message); - } + public PngjException(final String message) { + super(message); + } - public PngjException(Throwable cause) { - super(cause); - } + public PngjException(final Throwable cause) { + super(cause); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/PngjExceptionInternal.java b/teavm/src/main/java/ar/com/hjg/pngj/PngjExceptionInternal.java index 8059e35e..5113ac0e 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/PngjExceptionInternal.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/PngjExceptionInternal.java @@ -1,23 +1,24 @@ package ar.com.hjg.pngj; /** - * Exception for anomalous internal problems (sort of asserts) that point to some issue with the library - * + * Exception for anomalous internal problems (sort of asserts) that point to + * some issue with the library + * * @author Hernan J Gonzalez - * + * */ public class PngjExceptionInternal extends RuntimeException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public PngjExceptionInternal(String message, Throwable cause) { - super(message, cause); - } + public PngjExceptionInternal(final String message, final Throwable cause) { + super(message, cause); + } - public PngjExceptionInternal(String message) { - super(message); - } + public PngjExceptionInternal(final String message) { + super(message); + } - public PngjExceptionInternal(Throwable cause) { - super(cause); - } + public PngjExceptionInternal(final Throwable cause) { + super(cause); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/PngjInputException.java b/teavm/src/main/java/ar/com/hjg/pngj/PngjInputException.java index 668d6b68..8dbe7459 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/PngjInputException.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/PngjInputException.java @@ -4,17 +4,17 @@ package ar.com.hjg.pngj; * Exception thrown when reading a PNG. */ public class PngjInputException extends PngjException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public PngjInputException(String message, Throwable cause) { - super(message, cause); - } + public PngjInputException(final String message, final Throwable cause) { + super(message, cause); + } - public PngjInputException(String message) { - super(message); - } + public PngjInputException(final String message) { + super(message); + } - public PngjInputException(Throwable cause) { - super(cause); - } + public PngjInputException(final Throwable cause) { + super(cause); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/PngjOutputException.java b/teavm/src/main/java/ar/com/hjg/pngj/PngjOutputException.java index 6fea798c..3698c5b6 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/PngjOutputException.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/PngjOutputException.java @@ -4,17 +4,17 @@ package ar.com.hjg.pngj; * Exception thrown by writing process */ public class PngjOutputException extends PngjException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public PngjOutputException(String message, Throwable cause) { - super(message, cause); - } + public PngjOutputException(final String message, final Throwable cause) { + super(message, cause); + } - public PngjOutputException(String message) { - super(message); - } + public PngjOutputException(final String message) { + super(message); + } - public PngjOutputException(Throwable cause) { - super(cause); - } + public PngjOutputException(final Throwable cause) { + super(cause); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/PngjUnsupportedException.java b/teavm/src/main/java/ar/com/hjg/pngj/PngjUnsupportedException.java index 46290c20..2c2ae9b8 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/PngjUnsupportedException.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/PngjUnsupportedException.java @@ -1,24 +1,25 @@ package ar.com.hjg.pngj; /** - * Exception thrown because of some valid feature of PNG standard that this library does not support. + * Exception thrown because of some valid feature of PNG standard that this + * library does not support. */ public class PngjUnsupportedException extends RuntimeException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public PngjUnsupportedException() { - super(); - } + public PngjUnsupportedException() { + super(); + } - public PngjUnsupportedException(String message, Throwable cause) { - super(message, cause); - } + public PngjUnsupportedException(final String message, final Throwable cause) { + super(message, cause); + } - public PngjUnsupportedException(String message) { - super(message); - } + public PngjUnsupportedException(final String message) { + super(message); + } - public PngjUnsupportedException(Throwable cause) { - super(cause); - } + public PngjUnsupportedException(final Throwable cause) { + super(cause); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/RowInfo.java b/teavm/src/main/java/ar/com/hjg/pngj/RowInfo.java index e033989c..33f78ef2 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/RowInfo.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/RowInfo.java @@ -4,52 +4,52 @@ package ar.com.hjg.pngj; * Packs information of current row. Only used internally */ class RowInfo { - public final ImageInfo imgInfo; - public final Deinterlacer deinterlacer; - public final boolean imode; // Interlaced - int dY, dX, oY, oX; // current step and offset (in pixels) - int rowNseq; // row number (from 0) in sequential read order - int rowNreal; // row number in the real image - int rowNsubImg; // current row in the virtual subsampled image; this increments (by 1) from 0 to - // rows/dy 7 times - int rowsSubImg, colsSubImg; // size of current subimage , in pixels - int bytesRow; - int pass; // 1-7 - byte[] buf; // non-deep copy - int buflen; // valid bytes in buffer (include filter byte) + public final ImageInfo imgInfo; + public final Deinterlacer deinterlacer; + public final boolean imode; // Interlaced + int dY, dX, oY, oX; // current step and offset (in pixels) + int rowNseq; // row number (from 0) in sequential read order + int rowNreal; // row number in the real image + int rowNsubImg; // current row in the virtual subsampled image; this increments (by 1) from 0 to + // rows/dy 7 times + int rowsSubImg, colsSubImg; // size of current subimage , in pixels + int bytesRow; + int pass; // 1-7 + byte[] buf; // non-deep copy + int buflen; // valid bytes in buffer (include filter byte) - public RowInfo(ImageInfo imgInfo, Deinterlacer deinterlacer) { - this.imgInfo = imgInfo; - this.deinterlacer = deinterlacer; - this.imode = deinterlacer != null; - } + public RowInfo(final ImageInfo imgInfo, final Deinterlacer deinterlacer) { + this.imgInfo = imgInfo; + this.deinterlacer = deinterlacer; + imode = deinterlacer != null; + } - void update(int rowseq) { - rowNseq = rowseq; - if (imode) { - pass = deinterlacer.getPass(); - dX = deinterlacer.dX; - dY = deinterlacer.dY; - oX = deinterlacer.oX; - oY = deinterlacer.oY; - rowNreal = deinterlacer.getCurrRowReal(); - rowNsubImg = deinterlacer.getCurrRowSubimg(); - rowsSubImg = deinterlacer.getRows(); - colsSubImg = deinterlacer.getCols(); - bytesRow = (imgInfo.bitspPixel * colsSubImg + 7) / 8; - } else { - pass = 1; - dX = dY = 1; - oX = oY = 0; - rowNreal = rowNsubImg = rowseq; - rowsSubImg = imgInfo.rows; - colsSubImg = imgInfo.cols; - bytesRow = imgInfo.bytesPerRow; - } - } + void update(final int rowseq) { + rowNseq = rowseq; + if (imode) { + pass = deinterlacer.getPass(); + dX = deinterlacer.dX; + dY = deinterlacer.dY; + oX = deinterlacer.oX; + oY = deinterlacer.oY; + rowNreal = deinterlacer.getCurrRowReal(); + rowNsubImg = deinterlacer.getCurrRowSubimg(); + rowsSubImg = deinterlacer.getRows(); + colsSubImg = deinterlacer.getCols(); + bytesRow = (imgInfo.bitspPixel * colsSubImg + 7) / 8; + } else { + pass = 1; + dX = dY = 1; + oX = oY = 0; + rowNreal = rowNsubImg = rowseq; + rowsSubImg = imgInfo.rows; + colsSubImg = imgInfo.cols; + bytesRow = imgInfo.bytesPerRow; + } + } - void updateBuf(byte[] buf, int buflen) { - this.buf = buf; - this.buflen = buflen; - } + void updateBuf(final byte[] buf, final int buflen) { + this.buf = buf; + this.buflen = buflen; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkCopyBehaviour.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkCopyBehaviour.java index 9e292f50..95224556 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkCopyBehaviour.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkCopyBehaviour.java @@ -5,97 +5,93 @@ import ar.com.hjg.pngj.PngReader; import ar.com.hjg.pngj.PngWriter; /** - * Chunk copy policy to apply when copyng from a {@link PngReader} to a {@link PngWriter}. + * Chunk copy policy to apply when copyng from a {@link PngReader} to a + * {@link PngWriter}. *

* The constants are bit-masks, they can be OR-ed *

- * Reference: http://www.w3.org/TR/PNG/#14
+ * Reference: + * http://www.w3.org/TR/PNG/#14
*/ public class ChunkCopyBehaviour { - /** Don't copy anything */ - public static final int COPY_NONE = 0; + /** Don't copy anything */ + public static final int COPY_NONE = 0; - /** copy the palette */ - public static final int COPY_PALETTE = 1; + /** copy the palette */ + public static final int COPY_PALETTE = 1; - /** copy all 'safe to copy' chunks */ - public static final int COPY_ALL_SAFE = 1 << 2; + /** copy all 'safe to copy' chunks */ + public static final int COPY_ALL_SAFE = 1 << 2; - /** - * copy all, including palette - */ - public static final int COPY_ALL = 1 << 3; // includes palette! - /** - * Copy PHYS chunk (physical resolution) - */ - public static final int COPY_PHYS = 1 << 4; // dpi - /** - * Copy al textual chunks. - */ - public static final int COPY_TEXTUAL = 1 << 5; // all textual types - /** - * Copy TRNS chunk - */ - public static final int COPY_TRANSPARENCY = 1 << 6; // - /** - * Copy unknown chunks (unknown by our factory) - */ - public static final int COPY_UNKNOWN = 1 << 7; // all unknown (by the factory!) - /** - * Copy almost all: excepts only HIST (histogram) TIME and TEXTUAL chunks - */ - public static final int COPY_ALMOSTALL = 1 << 8; + /** + * copy all, including palette + */ + public static final int COPY_ALL = 1 << 3; // includes palette! + /** + * Copy PHYS chunk (physical resolution) + */ + public static final int COPY_PHYS = 1 << 4; // dpi + /** + * Copy al textual chunks. + */ + public static final int COPY_TEXTUAL = 1 << 5; // all textual types + /** + * Copy TRNS chunk + */ + public static final int COPY_TRANSPARENCY = 1 << 6; // + /** + * Copy unknown chunks (unknown by our factory) + */ + public static final int COPY_UNKNOWN = 1 << 7; // all unknown (by the factory!) + /** + * Copy almost all: excepts only HIST (histogram) TIME and TEXTUAL chunks + */ + public static final int COPY_ALMOSTALL = 1 << 8; - private static boolean maskMatch(int v, int mask) { - return (v & mask) != 0; - } + private static boolean maskMatch(final int v, final int mask) { + return (v & mask) != 0; + } - /** - * Creates a predicate equivalent to the copy mask - *

- * Given a copy mask (see static fields) and the ImageInfo of the target PNG, returns a predicate that tells if a - * chunk should be copied. - *

- * This is a handy helper method, you can also create and set your own predicate - */ - public static ChunkPredicate createPredicate(final int copyFromMask, final ImageInfo imgInfo) { - return new ChunkPredicate() { - public boolean match(PngChunk chunk) { - if (chunk.crit) { - if (chunk.id.equals(ChunkHelper.PLTE)) { - if (imgInfo.indexed && maskMatch(copyFromMask, ChunkCopyBehaviour.COPY_PALETTE)) - return true; - if (!imgInfo.greyscale && maskMatch(copyFromMask, ChunkCopyBehaviour.COPY_ALL)) - return true; - } - } else { // ancillary - boolean text = (chunk instanceof PngChunkTextVar); - boolean safe = chunk.safe; - // notice that these if are not exclusive - if (maskMatch(copyFromMask, ChunkCopyBehaviour.COPY_ALL)) - return true; - if (safe && maskMatch(copyFromMask, ChunkCopyBehaviour.COPY_ALL_SAFE)) - return true; - if (chunk.id.equals(ChunkHelper.tRNS) - && maskMatch(copyFromMask, ChunkCopyBehaviour.COPY_TRANSPARENCY)) - return true; - if (chunk.id.equals(ChunkHelper.pHYs) - && maskMatch(copyFromMask, ChunkCopyBehaviour.COPY_PHYS)) - return true; - if (text && maskMatch(copyFromMask, ChunkCopyBehaviour.COPY_TEXTUAL)) - return true; - if (maskMatch(copyFromMask, ChunkCopyBehaviour.COPY_ALMOSTALL) - && !(ChunkHelper.isUnknown(chunk) || text || chunk.id.equals(ChunkHelper.hIST) || chunk.id - .equals(ChunkHelper.tIME))) - return true; - if (maskMatch(copyFromMask, ChunkCopyBehaviour.COPY_UNKNOWN) - && ChunkHelper.isUnknown(chunk)) - return true; - } - return false; - } - - }; - } + /** + * Creates a predicate equivalent to the copy mask + *

+ * Given a copy mask (see static fields) and the ImageInfo of the target + * PNG, returns a predicate that tells if a + * chunk should be copied. + *

+ * This is a handy helper method, you can also create and set your own + * predicate + */ + public static ChunkPredicate createPredicate(final int copyFromMask, final ImageInfo imgInfo) { + return chunk -> { + if (chunk.crit) { + if (chunk.id.equals(ChunkHelper.PLTE)) { + if (imgInfo.indexed && ChunkCopyBehaviour.maskMatch(copyFromMask, ChunkCopyBehaviour.COPY_PALETTE)) + return true; + if (!imgInfo.greyscale && ChunkCopyBehaviour.maskMatch(copyFromMask, ChunkCopyBehaviour.COPY_ALL)) + return true; + } + } else { // ancillary + final boolean text = chunk instanceof PngChunkTextVar; + final boolean safe = chunk.safe; + // notice that these if are not exclusive + if (ChunkCopyBehaviour.maskMatch(copyFromMask, ChunkCopyBehaviour.COPY_ALL)) + return true; + if (safe && ChunkCopyBehaviour.maskMatch(copyFromMask, ChunkCopyBehaviour.COPY_ALL_SAFE)) + return true; + if (chunk.id.equals(ChunkHelper.tRNS) && ChunkCopyBehaviour.maskMatch(copyFromMask, ChunkCopyBehaviour.COPY_TRANSPARENCY)) + return true; + if (chunk.id.equals(ChunkHelper.pHYs) && ChunkCopyBehaviour.maskMatch(copyFromMask, ChunkCopyBehaviour.COPY_PHYS)) + return true; + if (text && ChunkCopyBehaviour.maskMatch(copyFromMask, ChunkCopyBehaviour.COPY_TEXTUAL)) + return true; + if (ChunkCopyBehaviour.maskMatch(copyFromMask, ChunkCopyBehaviour.COPY_ALMOSTALL) && !(ChunkHelper.isUnknown(chunk) || text || chunk.id.equals(ChunkHelper.hIST) || chunk.id.equals(ChunkHelper.tIME))) + return true; + if (ChunkCopyBehaviour.maskMatch(copyFromMask, ChunkCopyBehaviour.COPY_UNKNOWN) && ChunkHelper.isUnknown(chunk)) + return true; + } + return false; + }; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkFactory.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkFactory.java index 06969eca..351980c3 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkFactory.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkFactory.java @@ -6,102 +6,107 @@ import ar.com.hjg.pngj.ImageInfo; /** * Default chunk factory. *

- * The user that wants to parse custom chunks can extend {@link #createEmptyChunkExtended(String, ImageInfo)} + * The user that wants to parse custom chunks can extend + * {@link #createEmptyChunkExtended(String, ImageInfo)} */ public class ChunkFactory implements IChunkFactory { - boolean parse; + boolean parse; - public ChunkFactory() { - this(true); - } + public ChunkFactory() { + this(true); + } - public ChunkFactory(boolean parse) { - this.parse = parse; - } + public ChunkFactory(final boolean parse) { + this.parse = parse; + } - public final PngChunk createChunk(ChunkRaw chunkRaw, ImageInfo imgInfo) { - PngChunk c = createEmptyChunkKnown(chunkRaw.id, imgInfo); - if (c == null) - c = createEmptyChunkExtended(chunkRaw.id, imgInfo); - if (c == null) - c = createEmptyChunkUnknown(chunkRaw.id, imgInfo); - c.setRaw(chunkRaw); - if (parse && chunkRaw.data != null) - c.parseFromRaw(chunkRaw); - return c; - } + @Override + public final PngChunk createChunk(final ChunkRaw chunkRaw, final ImageInfo imgInfo) { + PngChunk c = createEmptyChunkKnown(chunkRaw.id, imgInfo); + if (c == null) + c = createEmptyChunkExtended(chunkRaw.id, imgInfo); + if (c == null) + c = createEmptyChunkUnknown(chunkRaw.id, imgInfo); + c.setRaw(chunkRaw); + if (parse && chunkRaw.data != null) + c.parseFromRaw(chunkRaw); + return c; + } - protected final PngChunk createEmptyChunkKnown(String id, ImageInfo imgInfo) { - if (id.equals(ChunkHelper.IDAT)) - return new PngChunkIDAT(imgInfo); - if (id.equals(ChunkHelper.IHDR)) - return new PngChunkIHDR(imgInfo); - if (id.equals(ChunkHelper.PLTE)) - return new PngChunkPLTE(imgInfo); - if (id.equals(ChunkHelper.IEND)) - return new PngChunkIEND(imgInfo); - if (id.equals(ChunkHelper.tEXt)) - return new PngChunkTEXT(imgInfo); - if (id.equals(ChunkHelper.iTXt)) - return new PngChunkITXT(imgInfo); - if (id.equals(ChunkHelper.zTXt)) - return new PngChunkZTXT(imgInfo); - if (id.equals(ChunkHelper.bKGD)) - return new PngChunkBKGD(imgInfo); - if (id.equals(ChunkHelper.gAMA)) - return new PngChunkGAMA(imgInfo); - if (id.equals(ChunkHelper.pHYs)) - return new PngChunkPHYS(imgInfo); - if (id.equals(ChunkHelper.iCCP)) - return new PngChunkICCP(imgInfo); - if (id.equals(ChunkHelper.tIME)) - return new PngChunkTIME(imgInfo); - if (id.equals(ChunkHelper.tRNS)) - return new PngChunkTRNS(imgInfo); - if (id.equals(ChunkHelper.cHRM)) - return new PngChunkCHRM(imgInfo); - if (id.equals(ChunkHelper.sBIT)) - return new PngChunkSBIT(imgInfo); - if (id.equals(ChunkHelper.sRGB)) - return new PngChunkSRGB(imgInfo); - if (id.equals(ChunkHelper.hIST)) - return new PngChunkHIST(imgInfo); - if (id.equals(ChunkHelper.sPLT)) - return new PngChunkSPLT(imgInfo); - // apng - if (id.equals(PngChunkFDAT.ID)) - return new PngChunkFDAT(imgInfo); - if (id.equals(PngChunkACTL.ID)) - return new PngChunkACTL(imgInfo); - if (id.equals(PngChunkFCTL.ID)) - return new PngChunkFCTL(imgInfo); - return null; - } + protected final PngChunk createEmptyChunkKnown(final String id, final ImageInfo imgInfo) { + if (id.equals(ChunkHelper.IDAT)) + return new PngChunkIDAT(imgInfo); + if (id.equals(ChunkHelper.IHDR)) + return new PngChunkIHDR(imgInfo); + if (id.equals(ChunkHelper.PLTE)) + return new PngChunkPLTE(imgInfo); + if (id.equals(ChunkHelper.IEND)) + return new PngChunkIEND(imgInfo); + if (id.equals(ChunkHelper.tEXt)) + return new PngChunkTEXT(imgInfo); + if (id.equals(ChunkHelper.iTXt)) + return new PngChunkITXT(imgInfo); + if (id.equals(ChunkHelper.zTXt)) + return new PngChunkZTXT(imgInfo); + if (id.equals(ChunkHelper.bKGD)) + return new PngChunkBKGD(imgInfo); + if (id.equals(ChunkHelper.gAMA)) + return new PngChunkGAMA(imgInfo); + if (id.equals(ChunkHelper.pHYs)) + return new PngChunkPHYS(imgInfo); + if (id.equals(ChunkHelper.iCCP)) + return new PngChunkICCP(imgInfo); + if (id.equals(ChunkHelper.tIME)) + return new PngChunkTIME(imgInfo); + if (id.equals(ChunkHelper.tRNS)) + return new PngChunkTRNS(imgInfo); + if (id.equals(ChunkHelper.cHRM)) + return new PngChunkCHRM(imgInfo); + if (id.equals(ChunkHelper.sBIT)) + return new PngChunkSBIT(imgInfo); + if (id.equals(ChunkHelper.sRGB)) + return new PngChunkSRGB(imgInfo); + if (id.equals(ChunkHelper.hIST)) + return new PngChunkHIST(imgInfo); + if (id.equals(ChunkHelper.sPLT)) + return new PngChunkSPLT(imgInfo); + // apng + if (id.equals(PngChunkFDAT.ID)) + return new PngChunkFDAT(imgInfo); + if (id.equals(PngChunkACTL.ID)) + return new PngChunkACTL(imgInfo); + if (id.equals(PngChunkFCTL.ID)) + return new PngChunkFCTL(imgInfo); + return null; + } - /** - * This is used as last resort factory method. - *

- * It creates a {@link PngChunkUNKNOWN} chunk. - */ - protected final PngChunk createEmptyChunkUnknown(String id, ImageInfo imgInfo) { - return new PngChunkUNKNOWN(id, imgInfo); - } + /** + * This is used as last resort factory method. + *

+ * It creates a {@link PngChunkUNKNOWN} chunk. + */ + protected final PngChunk createEmptyChunkUnknown(final String id, final ImageInfo imgInfo) { + return new PngChunkUNKNOWN(id, imgInfo); + } - /** - * Factory for chunks that are not in the original PNG standard. This can be overriden (but dont forget to call this - * also) - * - * @param id Chunk id , 4 letters - * @param imgInfo Usually not needed - * @return null if chunk id not recognized - */ - protected PngChunk createEmptyChunkExtended(String id, ImageInfo imgInfo) { - if (id.equals(PngChunkOFFS.ID)) - return new PngChunkOFFS(imgInfo); - if (id.equals(PngChunkSTER.ID)) - return new PngChunkSTER(imgInfo); - return null; // extend! - } + /** + * Factory for chunks that are not in the original PNG standard. This can be + * overriden (but dont forget to call this + * also) + * + * @param id + * Chunk id , 4 letters + * @param imgInfo + * Usually not needed + * @return null if chunk id not recognized + */ + protected PngChunk createEmptyChunkExtended(final String id, final ImageInfo imgInfo) { + if (id.equals(PngChunkOFFS.ID)) + return new PngChunkOFFS(imgInfo); + if (id.equals(PngChunkSTER.ID)) + return new PngChunkSTER(imgInfo); + return null; // extend! + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkHelper.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkHelper.java index 68858978..90fa8510 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkHelper.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkHelper.java @@ -21,270 +21,271 @@ import ar.com.hjg.pngj.PngjException; /** * Helper methods and constants related to Chunk processing. *

- * This should only be of interest to developers doing special chunk processing or extending the ChunkFactory + * This should only be of interest to developers doing special chunk processing + * or extending the ChunkFactory */ public class ChunkHelper { - ChunkHelper() {} + ChunkHelper() {} - public static final String IHDR = "IHDR"; - public static final String PLTE = "PLTE"; - public static final String IDAT = "IDAT"; - public static final String IEND = "IEND"; - public static final String cHRM = "cHRM"; - public static final String gAMA = "gAMA"; - public static final String iCCP = "iCCP"; - public static final String sBIT = "sBIT"; - public static final String sRGB = "sRGB"; - public static final String bKGD = "bKGD"; - public static final String hIST = "hIST"; - public static final String tRNS = "tRNS"; - public static final String pHYs = "pHYs"; - public static final String sPLT = "sPLT"; - public static final String tIME = "tIME"; - public static final String iTXt = "iTXt"; - public static final String tEXt = "tEXt"; - public static final String zTXt = "zTXt"; + public static final String IHDR = "IHDR"; + public static final String PLTE = "PLTE"; + public static final String IDAT = "IDAT"; + public static final String IEND = "IEND"; + public static final String cHRM = "cHRM"; + public static final String gAMA = "gAMA"; + public static final String iCCP = "iCCP"; + public static final String sBIT = "sBIT"; + public static final String sRGB = "sRGB"; + public static final String bKGD = "bKGD"; + public static final String hIST = "hIST"; + public static final String tRNS = "tRNS"; + public static final String pHYs = "pHYs"; + public static final String sPLT = "sPLT"; + public static final String tIME = "tIME"; + public static final String iTXt = "iTXt"; + public static final String tEXt = "tEXt"; + public static final String zTXt = "zTXt"; - public static final byte[] b_IHDR = toBytes(IHDR); - public static final byte[] b_PLTE = toBytes(PLTE); - public static final byte[] b_IDAT = toBytes(IDAT); - public static final byte[] b_IEND = toBytes(IEND); + public static final byte[] b_IHDR = ChunkHelper.toBytes(ChunkHelper.IHDR); + public static final byte[] b_PLTE = ChunkHelper.toBytes(ChunkHelper.PLTE); + public static final byte[] b_IDAT = ChunkHelper.toBytes(ChunkHelper.IDAT); + public static final byte[] b_IEND = ChunkHelper.toBytes(ChunkHelper.IEND); - /* - * static auxiliary buffer. any method that uses this should synchronize against this - */ - private static byte[] tmpbuffer = new byte[4096]; + /* + * static auxiliary buffer. any method that uses this should synchronize against this + */ + private static byte[] tmpbuffer = new byte[4096]; - /** - * Converts to bytes using Latin1 (ISO-8859-1) - */ - public static byte[] toBytes(String x) { - try { - return x.getBytes(PngHelperInternal.charsetLatin1name); - } catch (UnsupportedEncodingException e) { - throw new PngBadCharsetException(e); - } - } + /** + * Converts to bytes using Latin1 (ISO-8859-1) + */ + public static byte[] toBytes(final String x) { + try { + return x.getBytes(PngHelperInternal.charsetLatin1name); + } catch (final UnsupportedEncodingException e) { + throw new PngBadCharsetException(e); + } + } - /** - * Converts to String using Latin1 (ISO-8859-1) - */ - public static String toString(byte[] x) { - try { - return new String(x, PngHelperInternal.charsetLatin1name); - } catch (UnsupportedEncodingException e) { - throw new PngBadCharsetException(e); - } - } + /** + * Converts to String using Latin1 (ISO-8859-1) + */ + public static String toString(final byte[] x) { + try { + return new String(x, PngHelperInternal.charsetLatin1name); + } catch (final UnsupportedEncodingException e) { + throw new PngBadCharsetException(e); + } + } - /** - * Converts to String using Latin1 (ISO-8859-1) - */ - public static String toString(byte[] x, int offset, int len) { - try { - return new String(x, offset, len, PngHelperInternal.charsetLatin1name); - } catch (UnsupportedEncodingException e) { - throw new PngBadCharsetException(e); - } - } + /** + * Converts to String using Latin1 (ISO-8859-1) + */ + public static String toString(final byte[] x, final int offset, final int len) { + try { + return new String(x, offset, len, PngHelperInternal.charsetLatin1name); + } catch (final UnsupportedEncodingException e) { + throw new PngBadCharsetException(e); + } + } - /** - * Converts to bytes using UTF-8 - */ - public static byte[] toBytesUTF8(String x) { - try { - return x.getBytes(PngHelperInternal.charsetUTF8name); - } catch (UnsupportedEncodingException e) { - throw new PngBadCharsetException(e); - } - } + /** + * Converts to bytes using UTF-8 + */ + public static byte[] toBytesUTF8(final String x) { + try { + return x.getBytes(PngHelperInternal.charsetUTF8name); + } catch (final UnsupportedEncodingException e) { + throw new PngBadCharsetException(e); + } + } - /** - * Converts to string using UTF-8 - */ - public static String toStringUTF8(byte[] x) { - try { - return new String(x, PngHelperInternal.charsetUTF8name); - } catch (UnsupportedEncodingException e) { - throw new PngBadCharsetException(e); - } - } + /** + * Converts to string using UTF-8 + */ + public static String toStringUTF8(final byte[] x) { + try { + return new String(x, PngHelperInternal.charsetUTF8name); + } catch (final UnsupportedEncodingException e) { + throw new PngBadCharsetException(e); + } + } - /** - * Converts to string using UTF-8 - */ - public static String toStringUTF8(byte[] x, int offset, int len) { - try { - return new String(x, offset, len, PngHelperInternal.charsetUTF8name); - } catch (UnsupportedEncodingException e) { - throw new PngBadCharsetException(e); - } - } + /** + * Converts to string using UTF-8 + */ + public static String toStringUTF8(final byte[] x, final int offset, final int len) { + try { + return new String(x, offset, len, PngHelperInternal.charsetUTF8name); + } catch (final UnsupportedEncodingException e) { + throw new PngBadCharsetException(e); + } + } - /** - * critical chunk : first letter is uppercase - */ - public static boolean isCritical(String id) { - return (Character.isUpperCase(id.charAt(0))); - } + /** + * critical chunk : first letter is uppercase + */ + public static boolean isCritical(final String id) { + return Character.isUpperCase(id.charAt(0)); + } - /** - * public chunk: second letter is uppercase - */ - public static boolean isPublic(String id) { // - return (Character.isUpperCase(id.charAt(1))); - } + /** + * public chunk: second letter is uppercase + */ + public static boolean isPublic(final String id) { // + return Character.isUpperCase(id.charAt(1)); + } - /** - * Safe to copy chunk: fourth letter is lower case - */ - public static boolean isSafeToCopy(String id) { - return (!Character.isUpperCase(id.charAt(3))); - } + /** + * Safe to copy chunk: fourth letter is lower case + */ + public static boolean isSafeToCopy(final String id) { + return !Character.isUpperCase(id.charAt(3)); + } - /** - * "Unknown" just means that our chunk factory (even when it has been augmented by client code) did not recognize its - * id - */ - public static boolean isUnknown(PngChunk c) { - return c instanceof PngChunkUNKNOWN; - } + /** + * "Unknown" just means that our chunk factory (even when it has been + * augmented by client code) did not recognize its + * id + */ + public static boolean isUnknown(final PngChunk c) { + return c instanceof PngChunkUNKNOWN; + } - /** - * Finds position of null byte in array - * - * @param b - * @return -1 if not found - */ - public static int posNullByte(byte[] b) { - for (int i = 0; i < b.length; i++) - if (b[i] == 0) - return i; - return -1; - } + /** + * Finds position of null byte in array + * + * @param b + * @return -1 if not found + */ + public static int posNullByte(final byte[] b) { + for (int i = 0; i < b.length; i++) + if (b[i] == 0) + return i; + return -1; + } - /** - * Decides if a chunk should be loaded, according to a ChunkLoadBehaviour - * - * @param id - * @param behav - * @return true/false - */ - public static boolean shouldLoad(String id, ChunkLoadBehaviour behav) { - if (isCritical(id)) - return true; - switch (behav) { - case LOAD_CHUNK_ALWAYS: - return true; - case LOAD_CHUNK_IF_SAFE: - return isSafeToCopy(id); - case LOAD_CHUNK_NEVER: - return false; - case LOAD_CHUNK_MOST_IMPORTANT: - return id.equals(PngChunkTRNS.ID); - } - return false; // should not reach here - } + /** + * Decides if a chunk should be loaded, according to a ChunkLoadBehaviour + * + * @param id + * @param behav + * @return true/false + */ + public static boolean shouldLoad(final String id, final ChunkLoadBehaviour behav) { + if (ChunkHelper.isCritical(id)) + return true; + switch (behav) { + case LOAD_CHUNK_ALWAYS: + return true; + case LOAD_CHUNK_IF_SAFE: + return ChunkHelper.isSafeToCopy(id); + case LOAD_CHUNK_NEVER: + return false; + case LOAD_CHUNK_MOST_IMPORTANT: + return id.equals(PngChunkTRNS.ID); + } + return false; // should not reach here + } - public final static byte[] compressBytes(byte[] ori, boolean compress) { - return compressBytes(ori, 0, ori.length, compress); - } + public final static byte[] compressBytes(final byte[] ori, final boolean compress) { + return ChunkHelper.compressBytes(ori, 0, ori.length, compress); + } - public static byte[] compressBytes(byte[] ori, int offset, int len, boolean compress) { - try { - ByteArrayInputStream inb = new ByteArrayInputStream(ori, offset, len); - InputStream in = compress ? inb : new InflaterInputStream(inb); - ByteArrayOutputStream outb = new ByteArrayOutputStream(); - OutputStream out = compress ? new DeflaterOutputStream(outb) : outb; - shovelInToOut(in, out); - in.close(); - out.close(); - return outb.toByteArray(); - } catch (Exception e) { - throw new PngjException(e); - } - } + public static byte[] compressBytes(final byte[] ori, final int offset, final int len, final boolean compress) { + try { + final ByteArrayInputStream inb = new ByteArrayInputStream(ori, offset, len); + final InputStream in = compress ? inb : new InflaterInputStream(inb); + final ByteArrayOutputStream outb = new ByteArrayOutputStream(); + final OutputStream out = compress ? new DeflaterOutputStream(outb) : outb; + ChunkHelper.shovelInToOut(in, out); + in.close(); + out.close(); + return outb.toByteArray(); + } catch (final Exception e) { + throw new PngjException(e); + } + } - /** - * Shovels all data from an input stream to an output stream. - */ - private static void shovelInToOut(InputStream in, OutputStream out) throws IOException { - synchronized (tmpbuffer) { - int len; - while ((len = in.read(tmpbuffer)) > 0) { - out.write(tmpbuffer, 0, len); - } - } - } + /** + * Shovels all data from an input stream to an output stream. + */ + private static void shovelInToOut(final InputStream in, final OutputStream out) throws IOException { + synchronized (ChunkHelper.tmpbuffer) { + int len; + while ((len = in.read(ChunkHelper.tmpbuffer)) > 0) + out.write(ChunkHelper.tmpbuffer, 0, len); + } + } - /** - * Returns only the chunks that "match" the predicate - * - * See also trimList() - */ - public static List filterList(List target, ChunkPredicate predicateKeep) { - List result = new ArrayList(); - for (PngChunk element : target) { - if (predicateKeep.match(element)) { - result.add(element); - } - } - return result; - } + /** + * Returns only the chunks that "match" the predicate + * + * See also trimList() + */ + public static List filterList(final List target, final ChunkPredicate predicateKeep) { + final List result = new ArrayList<>(); + for (final PngChunk element : target) + if (predicateKeep.match(element)) + result.add(element); + return result; + } - /** - * Remove (in place) the chunks that "match" the predicate - * - * See also filterList - */ - public static int trimList(List target, ChunkPredicate predicateRemove) { - Iterator it = target.iterator(); - int cont = 0; - while (it.hasNext()) { - PngChunk c = it.next(); - if (predicateRemove.match(c)) { - it.remove(); - cont++; - } - } - return cont; - } + /** + * Remove (in place) the chunks that "match" the predicate + * + * See also filterList + */ + public static int trimList(final List target, final ChunkPredicate predicateRemove) { + final Iterator it = target.iterator(); + int cont = 0; + while (it.hasNext()) { + final PngChunk c = it.next(); + if (predicateRemove.match(c)) { + it.remove(); + cont++; + } + } + return cont; + } - /** - * Adhoc criteria: two ancillary chunks are "equivalent" ("practically same type") if they have same id and (perhaps, - * if multiple are allowed) if the match also in some "internal key" (eg: key for string values, palette for sPLT, - * etc) - * - * When we use this method, we implicitly assume that we don't allow/expect two "equivalent" chunks in a single PNG - * - * Notice that the use of this is optional, and that the PNG standard actually allows text chunks that have same key - * - * @return true if "equivalent" - */ - public static final boolean equivalent(PngChunk c1, PngChunk c2) { - if (c1 == c2) - return true; - if (c1 == null || c2 == null || !c1.id.equals(c2.id)) - return false; - if (c1.crit) - return false; - // same id - if (c1.getClass() != c2.getClass()) - return false; // should not happen - if (!c2.allowsMultiple()) - return true; - if (c1 instanceof PngChunkTextVar) { - return ((PngChunkTextVar) c1).getKey().equals(((PngChunkTextVar) c2).getKey()); - } - if (c1 instanceof PngChunkSPLT) { - return ((PngChunkSPLT) c1).getPalName().equals(((PngChunkSPLT) c2).getPalName()); - } - // unknown chunks that allow multiple? consider they don't match - return false; - } + /** + * Adhoc criteria: two ancillary chunks are "equivalent" ("practically same + * type") if they have same id and (perhaps, + * if multiple are allowed) if the match also in some "internal key" (eg: + * key for string values, palette for sPLT, + * etc) + * + * When we use this method, we implicitly assume that we don't allow/expect + * two "equivalent" chunks in a single PNG + * + * Notice that the use of this is optional, and that the PNG standard + * actually allows text chunks that have same key + * + * @return true if "equivalent" + */ + public static final boolean equivalent(final PngChunk c1, final PngChunk c2) { + if (c1 == c2) + return true; + if (c1 == null || c2 == null || !c1.id.equals(c2.id)) + return false; + if (c1.crit) + return false; + // same id + if (c1.getClass() != c2.getClass()) + return false; // should not happen + if (!c2.allowsMultiple()) + return true; + if (c1 instanceof PngChunkTextVar) + return ((PngChunkTextVar) c1).getKey().equals(((PngChunkTextVar) c2).getKey()); + if (c1 instanceof PngChunkSPLT) + return ((PngChunkSPLT) c1).getPalName().equals(((PngChunkSPLT) c2).getPalName()); + // unknown chunks that allow multiple? consider they don't match + return false; + } - public static boolean isText(PngChunk c) { - return c instanceof PngChunkTextVar; - } + public static boolean isText(final PngChunk c) { + return c instanceof PngChunkTextVar; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkLoadBehaviour.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkLoadBehaviour.java index 84b92f3f..855b8061 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkLoadBehaviour.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkLoadBehaviour.java @@ -3,24 +3,25 @@ package ar.com.hjg.pngj.chunks; /** * What to do with ancillary (non-critical) chunks when reading. *

- * + * */ public enum ChunkLoadBehaviour { - /** - * All non-critical chunks are skipped - */ - LOAD_CHUNK_NEVER, - /** - * Load chunk if "safe to copy" - */ - LOAD_CHUNK_IF_SAFE, - /** - * Load only most important chunk: TRNS - */ - LOAD_CHUNK_MOST_IMPORTANT, - /** - * Load all chunks.
- * Notice that other restrictions might apply, see PngReader.skipChunkMaxSize PngReader.skipChunkIds - */ - LOAD_CHUNK_ALWAYS; + /** + * All non-critical chunks are skipped + */ + LOAD_CHUNK_NEVER, + /** + * Load chunk if "safe to copy" + */ + LOAD_CHUNK_IF_SAFE, + /** + * Load only most important chunk: TRNS + */ + LOAD_CHUNK_MOST_IMPORTANT, + /** + * Load all chunks.
+ * Notice that other restrictions might apply, see + * PngReader.skipChunkMaxSize PngReader.skipChunkIds + */ + LOAD_CHUNK_ALWAYS; } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkPredicate.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkPredicate.java index 72b2a6f3..2f9da63a 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkPredicate.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkPredicate.java @@ -4,11 +4,11 @@ package ar.com.hjg.pngj.chunks; * Decides if another chunk "matches", according to some criterion */ public interface ChunkPredicate { - /** - * The other chunk matches with this one - * - * @param chunk - * @return true if match - */ - boolean match(PngChunk chunk); + /** + * The other chunk matches with this one + * + * @param chunk + * @return true if match + */ + boolean match(PngChunk chunk); } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkRaw.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkRaw.java index e02a8fb6..7e23476d 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkRaw.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunkRaw.java @@ -12,158 +12,164 @@ import ar.com.hjg.pngj.PngjOutputException; /** * Raw (physical) chunk. *

- * Short lived object, to be created while serialing/deserializing Do not reuse it for different chunks.
+ * Short lived object, to be created while serialing/deserializing Do not reuse + * it for different chunks.
* See http://www.libpng.org/pub/png/spec/1.2/PNG-Structure.html */ public class ChunkRaw { - /** - * The length counts only the data field, not itself, the chunk type code, or the CRC. Zero is a valid length. - * Although encoders and decoders should treat the length as unsigned, its value must not exceed 231-1 bytes. - */ - public final int len; + /** + * The length counts only the data field, not itself, the chunk type code, + * or the CRC. Zero is a valid length. + * Although encoders and decoders should treat the length as unsigned, its + * value must not exceed 231-1 bytes. + */ + public final int len; - /** - * A 4-byte chunk type code. uppercase and lowercase ASCII letters - */ - public final byte[] idbytes; - public final String id; + /** + * A 4-byte chunk type code. uppercase and lowercase ASCII letters + */ + public final byte[] idbytes; + public final String id; - /** - * The data bytes appropriate to the chunk type, if any. This field can be of zero length. Does not include crc. If - * it's null, it means that the data is ot available - */ - public byte[] data = null; - /** - * @see ChunkRaw#getOffset() - */ - private long offset = 0; + /** + * The data bytes appropriate to the chunk type, if any. This field can be + * of zero length. Does not include crc. If + * it's null, it means that the data is ot available + */ + public byte[] data = null; + /** + * @see ChunkRaw#getOffset() + */ + private long offset = 0; - /** - * A 4-byte CRC (Cyclic Redundancy Check) calculated on the preceding bytes in the chunk, including the chunk type - * code and chunk data fields, but not including the length field. - */ - public byte[] crcval = new byte[4]; + /** + * A 4-byte CRC (Cyclic Redundancy Check) calculated on the preceding bytes + * in the chunk, including the chunk type + * code and chunk data fields, but not including the length field. + */ + public byte[] crcval = new byte[4]; - private CRC32 crcengine; // lazily instantiated + private CRC32 crcengine; // lazily instantiated - public ChunkRaw(int len, String id, boolean alloc) { - this.len = len; - this.id = id; - this.idbytes = ChunkHelper.toBytes(id); - for (int i = 0; i < 4; i++) { - if (idbytes[i] < 65 || idbytes[i] > 122 || (idbytes[i] > 90 && idbytes[i] < 97)) - throw new PngjException("Bad id chunk: must be ascii letters " + id); - } - if (alloc) - allocData(); - } + public ChunkRaw(final int len, final String id, final boolean alloc) { + this.len = len; + this.id = id; + idbytes = ChunkHelper.toBytes(id); + for (int i = 0; i < 4; i++) + if (idbytes[i] < 65 || idbytes[i] > 122 || idbytes[i] > 90 && idbytes[i] < 97) + throw new PngjException("Bad id chunk: must be ascii letters " + id); + if (alloc) + allocData(); + } - public ChunkRaw(int len, byte[] idbytes, boolean alloc) { - this(len, ChunkHelper.toString(idbytes), alloc); - } + public ChunkRaw(final int len, final byte[] idbytes, final boolean alloc) { + this(len, ChunkHelper.toString(idbytes), alloc); + } - public void allocData() { // TODO: not public - if (data == null || data.length < len) - data = new byte[len]; - } + public void allocData() { // TODO: not public + if (data == null || data.length < len) + data = new byte[len]; + } - /** - * this is called after setting data, before writing to os - */ - private void computeCrcForWriting() { - crcengine = new CRC32(); - crcengine.update(idbytes, 0, 4); - if (len > 0) - crcengine.update(data, 0, len); // - PngHelperInternal.writeInt4tobytes((int) crcengine.getValue(), crcval, 0); - } + /** + * this is called after setting data, before writing to os + */ + private void computeCrcForWriting() { + crcengine = new CRC32(); + crcengine.update(idbytes, 0, 4); + if (len > 0) + crcengine.update(data, 0, len); // + PngHelperInternal.writeInt4tobytes((int) crcengine.getValue(), crcval, 0); + } - /** - * Computes the CRC and writes to the stream. If error, a PngjOutputException is thrown - * - * Note that this is only used for non idat chunks - */ - public void writeChunk(OutputStream os) { - writeChunkHeader(os); - if (len > 0) { - if (data == null) - throw new PngjOutputException("cannot write chunk, raw chunk data is null [" + id + "]"); - PngHelperInternal.writeBytes(os, data, 0, len); - } - computeCrcForWriting(); - writeChunkCrc(os); - } + /** + * Computes the CRC and writes to the stream. If error, a + * PngjOutputException is thrown + * + * Note that this is only used for non idat chunks + */ + public void writeChunk(final OutputStream os) { + writeChunkHeader(os); + if (len > 0) { + if (data == null) + throw new PngjOutputException("cannot write chunk, raw chunk data is null [" + id + "]"); + PngHelperInternal.writeBytes(os, data, 0, len); + } + computeCrcForWriting(); + writeChunkCrc(os); + } - public void writeChunkHeader(OutputStream os) { - if (idbytes.length != 4) - throw new PngjOutputException("bad chunkid [" + id + "]"); - PngHelperInternal.writeInt4(os, len); - PngHelperInternal.writeBytes(os, idbytes); - } + public void writeChunkHeader(final OutputStream os) { + if (idbytes.length != 4) + throw new PngjOutputException("bad chunkid [" + id + "]"); + PngHelperInternal.writeInt4(os, len); + PngHelperInternal.writeBytes(os, idbytes); + } - public void writeChunkCrc(OutputStream os) { - PngHelperInternal.writeBytes(os, crcval, 0, 4); - } + public void writeChunkCrc(final OutputStream os) { + PngHelperInternal.writeBytes(os, crcval, 0, 4); + } - public void checkCrc() { - int crcComputed = (int) crcengine.getValue(); - int crcExpected = PngHelperInternal.readInt4fromBytes(crcval, 0); - if (crcComputed != crcExpected) - throw new PngjBadCrcException("chunk: " + this.toString() + " expected=" + crcExpected - + " read=" + crcComputed); - } + public void checkCrc() { + final int crcComputed = (int) crcengine.getValue(); + final int crcExpected = PngHelperInternal.readInt4fromBytes(crcval, 0); + if (crcComputed != crcExpected) + throw new PngjBadCrcException("chunk: " + toString() + " expected=" + crcExpected + " read=" + crcComputed); + } - public void updateCrc(byte[] buf, int off, int len) { - if (crcengine == null) - crcengine = new CRC32(); - crcengine.update(buf, off, len); - } + public void updateCrc(final byte[] buf, final int off, final int len) { + if (crcengine == null) + crcengine = new CRC32(); + crcengine.update(buf, off, len); + } - ByteArrayInputStream getAsByteStream() { // only the data - return new ByteArrayInputStream(data); - } + ByteArrayInputStream getAsByteStream() { // only the data + return new ByteArrayInputStream(data); + } - /** - * offset in the full PNG stream, in bytes. only informational, for read chunks (0=NA) - */ - public long getOffset() { - return offset; - } + /** + * offset in the full PNG stream, in bytes. only informational, for read + * chunks (0=NA) + */ + public long getOffset() { + return offset; + } - public void setOffset(long offset) { - this.offset = offset; - } + public void setOffset(final long offset) { + this.offset = offset; + } - public String toString() { - return "chunkid=" + ChunkHelper.toString(idbytes) + " len=" + len; - } + @Override + public String toString() { + return "chunkid=" + ChunkHelper.toString(idbytes) + " len=" + len; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + (int) (offset ^ (offset >>> 32)); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (id == null ? 0 : id.hashCode()); + result = prime * result + (int) (offset ^ offset >>> 32); + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ChunkRaw other = (ChunkRaw) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (offset != other.offset) - return false; - return true; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final ChunkRaw other = (ChunkRaw) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (offset != other.offset) + return false; + return true; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunksList.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunksList.java index f028c67c..50159b79 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunksList.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunksList.java @@ -12,156 +12,149 @@ import ar.com.hjg.pngj.PngjException; * chunks include all chunks, but IDAT is a single pseudo chunk without data **/ public class ChunksList { - // ref: http://www.w3.org/TR/PNG/#table53 - public static final int CHUNK_GROUP_0_IDHR = 0; // required - single - public static final int CHUNK_GROUP_1_AFTERIDHR = 1; // optional - multiple - public static final int CHUNK_GROUP_2_PLTE = 2; // optional - single - public static final int CHUNK_GROUP_3_AFTERPLTE = 3; // optional - multple - public static final int CHUNK_GROUP_4_IDAT = 4; // required (single pseudo chunk) - public static final int CHUNK_GROUP_5_AFTERIDAT = 5; // optional - multple - public static final int CHUNK_GROUP_6_END = 6; // only 1 chunk - requried + // ref: http://www.w3.org/TR/PNG/#table53 + public static final int CHUNK_GROUP_0_IDHR = 0; // required - single + public static final int CHUNK_GROUP_1_AFTERIDHR = 1; // optional - multiple + public static final int CHUNK_GROUP_2_PLTE = 2; // optional - single + public static final int CHUNK_GROUP_3_AFTERPLTE = 3; // optional - multple + public static final int CHUNK_GROUP_4_IDAT = 4; // required (single pseudo chunk) + public static final int CHUNK_GROUP_5_AFTERIDAT = 5; // optional - multple + public static final int CHUNK_GROUP_6_END = 6; // only 1 chunk - requried - /** - * All chunks, read (or written) - * - * But IDAT is a single pseudo chunk without data - */ - List chunks = new ArrayList(); - // protected HashMap> chunksById = new HashMap>(); - // // does not include IDAT + /** + * All chunks, read (or written) + * + * But IDAT is a single pseudo chunk without data + */ + List chunks = new ArrayList<>(); + // protected HashMap> chunksById = new HashMap>(); + // // does not include IDAT - final ImageInfo imageInfo; // only required for writing + final ImageInfo imageInfo; // only required for writing - boolean withPlte = false; + boolean withPlte = false; - public ChunksList(ImageInfo imfinfo) { - this.imageInfo = imfinfo; - } + public ChunksList(final ImageInfo imfinfo) { + imageInfo = imfinfo; + } - /** - * WARNING: this does NOT return a copy, but the list itself. The called should not modify this directly! Don't use - * this to manipulate the chunks. - */ - public List getChunks() { - return chunks; - } + /** + * WARNING: this does NOT return a copy, but the list itself. The called + * should not modify this directly! Don't use + * this to manipulate the chunks. + */ + public List getChunks() { + return chunks; + } - protected static List getXById(final List list, final String id, - final String innerid) { - if (innerid == null) - return ChunkHelper.filterList(list, new ChunkPredicate() { - public boolean match(PngChunk c) { - return c.id.equals(id); - } - }); - else - return ChunkHelper.filterList(list, new ChunkPredicate() { - public boolean match(PngChunk c) { - if (!c.id.equals(id)) - return false; - if (c instanceof PngChunkTextVar && !((PngChunkTextVar) c).getKey().equals(innerid)) - return false; - if (c instanceof PngChunkSPLT && !((PngChunkSPLT) c).getPalName().equals(innerid)) - return false; - return true; - } - }); - } + protected static List getXById(final List list, final String id, final String innerid) { + if (innerid == null) + return ChunkHelper.filterList(list, c -> c.id.equals(id)); + else + return ChunkHelper.filterList(list, c -> { + if (!c.id.equals(id)) + return false; + if (c instanceof PngChunkTextVar && !((PngChunkTextVar) c).getKey().equals(innerid)) + return false; + if (c instanceof PngChunkSPLT && !((PngChunkSPLT) c).getPalName().equals(innerid)) + return false; + return true; + }); + } - /** - * Adds chunk in next position. This is used onyl by the pngReader - */ - public void appendReadChunk(PngChunk chunk, int chunkGroup) { - chunk.setChunkGroup(chunkGroup); - chunks.add(chunk); - if (chunk.id.equals(PngChunkPLTE.ID)) - withPlte = true; - } + /** + * Adds chunk in next position. This is used onyl by the pngReader + */ + public void appendReadChunk(final PngChunk chunk, final int chunkGroup) { + chunk.setChunkGroup(chunkGroup); + chunks.add(chunk); + if (chunk.id.equals(PngChunkPLTE.ID)) + withPlte = true; + } - /** - * All chunks with this ID - * - * @param id - * @return List, empty if none - */ - public List getById(final String id) { - return getById(id, null); - } + /** + * All chunks with this ID + * + * @param id + * @return List, empty if none + */ + public List getById(final String id) { + return getById(id, null); + } - /** - * If innerid!=null and the chunk is PngChunkTextVar or PngChunkSPLT, it's filtered by that id - * - * @param id - * @return innerid Only used for text and SPLT chunks - * @return List, empty if none - */ - public List getById(final String id, final String innerid) { - return getXById(chunks, id, innerid); - } + /** + * If innerid!=null and the chunk is PngChunkTextVar or PngChunkSPLT, it's + * filtered by that id + * + * @param id + * @return innerid Only used for text and SPLT chunks + * @return List, empty if none + */ + public List getById(final String id, final String innerid) { + return ChunksList.getXById(chunks, id, innerid); + } - /** - * Returns only one chunk - * - * @param id - * @return First chunk found, null if not found - */ - public PngChunk getById1(final String id) { - return getById1(id, false); - } + /** + * Returns only one chunk + * + * @param id + * @return First chunk found, null if not found + */ + public PngChunk getById1(final String id) { + return getById1(id, false); + } - /** - * Returns only one chunk or null if nothing found - does not include queued - *

- * If more than one chunk is found, then an exception is thrown (failifMultiple=true or chunk is single) or the last - * one is returned (failifMultiple=false) - **/ - public PngChunk getById1(final String id, final boolean failIfMultiple) { - return getById1(id, null, failIfMultiple); - } + /** + * Returns only one chunk or null if nothing found - does not include queued + *

+ * If more than one chunk is found, then an exception is thrown + * (failifMultiple=true or chunk is single) or the last + * one is returned (failifMultiple=false) + **/ + public PngChunk getById1(final String id, final boolean failIfMultiple) { + return getById1(id, null, failIfMultiple); + } - /** - * Returns only one chunk or null if nothing found - does not include queued - *

- * If more than one chunk (after filtering by inner id) is found, then an exception is thrown (failifMultiple=true or - * chunk is single) or the last one is returned (failifMultiple=false) - **/ - public PngChunk getById1(final String id, final String innerid, final boolean failIfMultiple) { - List list = getById(id, innerid); - if (list.isEmpty()) - return null; - if (list.size() > 1 && (failIfMultiple || !list.get(0).allowsMultiple())) - throw new PngjException("unexpected multiple chunks id=" + id); - return list.get(list.size() - 1); - } + /** + * Returns only one chunk or null if nothing found - does not include queued + *

+ * If more than one chunk (after filtering by inner id) is found, then an + * exception is thrown (failifMultiple=true or + * chunk is single) or the last one is returned (failifMultiple=false) + **/ + public PngChunk getById1(final String id, final String innerid, final boolean failIfMultiple) { + final List list = getById(id, innerid); + if (list.isEmpty()) + return null; + if (list.size() > 1 && (failIfMultiple || !list.get(0).allowsMultiple())) + throw new PngjException("unexpected multiple chunks id=" + id); + return list.get(list.size() - 1); + } - /** - * Finds all chunks "equivalent" to this one - * - * @param c2 - * @return Empty if nothing found - */ - public List getEquivalent(final PngChunk c2) { - return ChunkHelper.filterList(chunks, new ChunkPredicate() { - public boolean match(PngChunk c) { - return ChunkHelper.equivalent(c, c2); - } - }); - } + /** + * Finds all chunks "equivalent" to this one + * + * @param c2 + * @return Empty if nothing found + */ + public List getEquivalent(final PngChunk c2) { + return ChunkHelper.filterList(chunks, c -> ChunkHelper.equivalent(c, c2)); + } - public String toString() { - return "ChunkList: read: " + chunks.size(); - } + @Override + public String toString() { + return "ChunkList: read: " + chunks.size(); + } - /** - * for debugging - */ - public String toStringFull() { - StringBuilder sb = new StringBuilder(toString()); - sb.append("\n Read:\n"); - for (PngChunk chunk : chunks) { - sb.append(chunk).append(" G=" + chunk.getChunkGroup() + "\n"); - } - return sb.toString(); - } + /** + * for debugging + */ + public String toStringFull() { + final StringBuilder sb = new StringBuilder(toString()); + sb.append("\n Read:\n"); + for (final PngChunk chunk : chunks) + sb.append(chunk).append(" G=" + chunk.getChunkGroup() + "\n"); + return sb.toString(); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunksListForWrite.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunksListForWrite.java index c2e58d7f..ec2d8669 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunksListForWrite.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/ChunksListForWrite.java @@ -12,178 +12,174 @@ import ar.com.hjg.pngj.PngjOutputException; public class ChunksListForWrite extends ChunksList { - /** - * chunks not yet writen - does not include IHDR, IDAT, END, perhaps yes PLTE - */ - private final List queuedChunks = new ArrayList(); + /** + * chunks not yet writen - does not include IHDR, IDAT, END, perhaps yes + * PLTE + */ + private final List queuedChunks = new ArrayList<>(); - // redundant, just for eficciency - private HashMap alreadyWrittenKeys = new HashMap(); + // redundant, just for eficciency + private final HashMap alreadyWrittenKeys = new HashMap<>(); - public ChunksListForWrite(ImageInfo imfinfo) { - super(imfinfo); - } + public ChunksListForWrite(final ImageInfo imfinfo) { + super(imfinfo); + } - /** - * Same as getById(), but looking in the queued chunks - */ - public List getQueuedById(final String id) { - return getQueuedById(id, null); - } + /** + * Same as getById(), but looking in the queued chunks + */ + public List getQueuedById(final String id) { + return getQueuedById(id, null); + } - /** - * Same as getById(), but looking in the queued chunks - */ - public List getQueuedById(final String id, final String innerid) { - return getXById(queuedChunks, id, innerid); - } + /** + * Same as getById(), but looking in the queued chunks + */ + public List getQueuedById(final String id, final String innerid) { + return ChunksList.getXById(queuedChunks, id, innerid); + } - /** - * Same as getById1(), but looking in the queued chunks - **/ - public PngChunk getQueuedById1(final String id, final String innerid, final boolean failIfMultiple) { - List list = getQueuedById(id, innerid); - if (list.isEmpty()) - return null; - if (list.size() > 1 && (failIfMultiple || !list.get(0).allowsMultiple())) - throw new PngjException("unexpected multiple chunks id=" + id); - return list.get(list.size() - 1); - } + /** + * Same as getById1(), but looking in the queued chunks + **/ + public PngChunk getQueuedById1(final String id, final String innerid, final boolean failIfMultiple) { + final List list = getQueuedById(id, innerid); + if (list.isEmpty()) + return null; + if (list.size() > 1 && (failIfMultiple || !list.get(0).allowsMultiple())) + throw new PngjException("unexpected multiple chunks id=" + id); + return list.get(list.size() - 1); + } - /** - * Same as getById1(), but looking in the queued chunks - **/ - public PngChunk getQueuedById1(final String id, final boolean failIfMultiple) { - return getQueuedById1(id, null, failIfMultiple); - } + /** + * Same as getById1(), but looking in the queued chunks + **/ + public PngChunk getQueuedById1(final String id, final boolean failIfMultiple) { + return getQueuedById1(id, null, failIfMultiple); + } - /** - * Same as getById1(), but looking in the queued chunks - **/ - public PngChunk getQueuedById1(final String id) { - return getQueuedById1(id, false); - } + /** + * Same as getById1(), but looking in the queued chunks + **/ + public PngChunk getQueuedById1(final String id) { + return getQueuedById1(id, false); + } - /** - * Finds all chunks "equivalent" to this one - * - * @param c2 - * @return Empty if nothing found - */ - public List getQueuedEquivalent(final PngChunk c2) { - return ChunkHelper.filterList(queuedChunks, new ChunkPredicate() { - public boolean match(PngChunk c) { - return ChunkHelper.equivalent(c, c2); - } - }); - } + /** + * Finds all chunks "equivalent" to this one + * + * @param c2 + * @return Empty if nothing found + */ + public List getQueuedEquivalent(final PngChunk c2) { + return ChunkHelper.filterList(queuedChunks, c -> ChunkHelper.equivalent(c, c2)); + } - /** - * Remove Chunk: only from queued - * - * WARNING: this depends on c.equals() implementation, which is straightforward for SingleChunks. For MultipleChunks, - * it will normally check for reference equality! - */ - public boolean removeChunk(PngChunk c) { - if (c == null) - return false; - return queuedChunks.remove(c); - } + /** + * Remove Chunk: only from queued + * + * WARNING: this depends on c.equals() implementation, which is + * straightforward for SingleChunks. For MultipleChunks, + * it will normally check for reference equality! + */ + public boolean removeChunk(final PngChunk c) { + if (c == null) + return false; + return queuedChunks.remove(c); + } - /** - * Adds chunk to queue - * - * If there - * - * @param c - */ - public boolean queue(PngChunk c) { - queuedChunks.add(c); - return true; - } + /** + * Adds chunk to queue + * + * If there + * + * @param c + */ + public boolean queue(final PngChunk c) { + queuedChunks.add(c); + return true; + } - /** - * this should be called only for ancillary chunks and PLTE (groups 1 - 3 - 5) - **/ - private static boolean shouldWrite(PngChunk c, int currentGroup) { - if (currentGroup == CHUNK_GROUP_2_PLTE) - return c.id.equals(ChunkHelper.PLTE); - if (currentGroup % 2 == 0) - throw new PngjOutputException("bad chunk group?"); - int minChunkGroup, maxChunkGroup; - if (c.getOrderingConstraint().mustGoBeforePLTE()) - minChunkGroup = maxChunkGroup = ChunksList.CHUNK_GROUP_1_AFTERIDHR; - else if (c.getOrderingConstraint().mustGoBeforeIDAT()) { - maxChunkGroup = ChunksList.CHUNK_GROUP_3_AFTERPLTE; - minChunkGroup = - c.getOrderingConstraint().mustGoAfterPLTE() ? ChunksList.CHUNK_GROUP_3_AFTERPLTE - : ChunksList.CHUNK_GROUP_1_AFTERIDHR; - } else { - maxChunkGroup = ChunksList.CHUNK_GROUP_5_AFTERIDAT; - minChunkGroup = ChunksList.CHUNK_GROUP_1_AFTERIDHR; - } + /** + * this should be called only for ancillary chunks and PLTE (groups 1 - 3 - + * 5) + **/ + private static boolean shouldWrite(final PngChunk c, final int currentGroup) { + if (currentGroup == ChunksList.CHUNK_GROUP_2_PLTE) + return c.id.equals(ChunkHelper.PLTE); + if (currentGroup % 2 == 0) + throw new PngjOutputException("bad chunk group?"); + int minChunkGroup, maxChunkGroup; + if (c.getOrderingConstraint().mustGoBeforePLTE()) + minChunkGroup = maxChunkGroup = ChunksList.CHUNK_GROUP_1_AFTERIDHR; + else if (c.getOrderingConstraint().mustGoBeforeIDAT()) { + maxChunkGroup = ChunksList.CHUNK_GROUP_3_AFTERPLTE; + minChunkGroup = c.getOrderingConstraint().mustGoAfterPLTE() ? ChunksList.CHUNK_GROUP_3_AFTERPLTE : ChunksList.CHUNK_GROUP_1_AFTERIDHR; + } else { + maxChunkGroup = ChunksList.CHUNK_GROUP_5_AFTERIDAT; + minChunkGroup = ChunksList.CHUNK_GROUP_1_AFTERIDHR; + } - int preferred = maxChunkGroup; - if (c.hasPriority()) - preferred = minChunkGroup; - if (ChunkHelper.isUnknown(c) && c.getChunkGroup() > 0) - preferred = c.getChunkGroup(); - if (currentGroup == preferred) - return true; - if (currentGroup > preferred && currentGroup <= maxChunkGroup) - return true; - return false; - } + int preferred = maxChunkGroup; + if (c.hasPriority()) + preferred = minChunkGroup; + if (ChunkHelper.isUnknown(c) && c.getChunkGroup() > 0) + preferred = c.getChunkGroup(); + if (currentGroup == preferred) + return true; + if (currentGroup > preferred && currentGroup <= maxChunkGroup) + return true; + return false; + } - public int writeChunks(OutputStream os, int currentGroup) { - int cont = 0; - Iterator it = queuedChunks.iterator(); - while (it.hasNext()) { - PngChunk c = it.next(); - if (!shouldWrite(c, currentGroup)) - continue; - if (ChunkHelper.isCritical(c.id) && !c.id.equals(ChunkHelper.PLTE)) - throw new PngjOutputException("bad chunk queued: " + c); - if (alreadyWrittenKeys.containsKey(c.id) && !c.allowsMultiple()) - throw new PngjOutputException("duplicated chunk does not allow multiple: " + c); - c.write(os); - chunks.add(c); - alreadyWrittenKeys.put(c.id, - alreadyWrittenKeys.containsKey(c.id) ? alreadyWrittenKeys.get(c.id) + 1 : 1); - c.setChunkGroup(currentGroup); - it.remove(); - cont++; - } - return cont; - } + public int writeChunks(final OutputStream os, final int currentGroup) { + int cont = 0; + final Iterator it = queuedChunks.iterator(); + while (it.hasNext()) { + final PngChunk c = it.next(); + if (!ChunksListForWrite.shouldWrite(c, currentGroup)) + continue; + if (ChunkHelper.isCritical(c.id) && !c.id.equals(ChunkHelper.PLTE)) + throw new PngjOutputException("bad chunk queued: " + c); + if (alreadyWrittenKeys.containsKey(c.id) && !c.allowsMultiple()) + throw new PngjOutputException("duplicated chunk does not allow multiple: " + c); + c.write(os); + chunks.add(c); + alreadyWrittenKeys.put(c.id, alreadyWrittenKeys.containsKey(c.id) ? alreadyWrittenKeys.get(c.id) + 1 : 1); + c.setChunkGroup(currentGroup); + it.remove(); + cont++; + } + return cont; + } - /** - * warning: this is NOT a copy, do not modify - */ - public List getQueuedChunks() { - return queuedChunks; - } + /** + * warning: this is NOT a copy, do not modify + */ + public List getQueuedChunks() { + return queuedChunks; + } - public String toString() { - return "ChunkList: written: " + getChunks().size() + " queue: " + queuedChunks.size(); - } + @Override + public String toString() { + return "ChunkList: written: " + getChunks().size() + " queue: " + queuedChunks.size(); + } - /** - * for debugging - */ - public String toStringFull() { - StringBuilder sb = new StringBuilder(toString()); - sb.append("\n Written:\n"); - for (PngChunk chunk : getChunks()) { - sb.append(chunk).append(" G=" + chunk.getChunkGroup() + "\n"); - } - if (!queuedChunks.isEmpty()) { - sb.append(" Queued:\n"); - for (PngChunk chunk : queuedChunks) { - sb.append(chunk).append("\n"); - } + /** + * for debugging + */ + @Override + public String toStringFull() { + final StringBuilder sb = new StringBuilder(toString()); + sb.append("\n Written:\n"); + for (final PngChunk chunk : getChunks()) + sb.append(chunk).append(" G=" + chunk.getChunkGroup() + "\n"); + if (!queuedChunks.isEmpty()) { + sb.append(" Queued:\n"); + for (final PngChunk chunk : queuedChunks) + sb.append(chunk).append("\n"); - } - return sb.toString(); - } + } + return sb.toString(); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngBadCharsetException.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngBadCharsetException.java index cc41c064..fe9df9e7 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngBadCharsetException.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngBadCharsetException.java @@ -3,18 +3,18 @@ package ar.com.hjg.pngj.chunks; import ar.com.hjg.pngj.PngjException; public class PngBadCharsetException extends PngjException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public PngBadCharsetException(String message, Throwable cause) { - super(message, cause); - } + public PngBadCharsetException(final String message, final Throwable cause) { + super(message, cause); + } - public PngBadCharsetException(String message) { - super(message); - } + public PngBadCharsetException(final String message) { + super(message); + } - public PngBadCharsetException(Throwable cause) { - super(cause); - } + public PngBadCharsetException(final Throwable cause) { + super(cause); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunk.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunk.java index 16b82204..2ffb837c 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunk.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunk.java @@ -8,209 +8,220 @@ import ar.com.hjg.pngj.PngjExceptionInternal; /** * Represents a instance of a PNG chunk. *

- * See http://www + * See + * http://www * .libpng.org/pub/png/spec/1.2/PNG-Chunks .html *

- * Concrete classes should extend {@link PngChunkSingle} or {@link PngChunkMultiple} + * Concrete classes should extend {@link PngChunkSingle} or + * {@link PngChunkMultiple} *

- * Note that some methods/fields are type-specific (getOrderingConstraint(), allowsMultiple()),
- * some are 'almost' type-specific (id,crit,pub,safe; the exception is PngUKNOWN),
+ * Note that some methods/fields are type-specific (getOrderingConstraint(), + * allowsMultiple()),
+ * some are 'almost' type-specific (id,crit,pub,safe; the exception is + * PngUKNOWN),
* and the rest are instance-specific */ public abstract class PngChunk { - /** - * Chunk-id: 4 letters - */ - public final String id; - /** - * Autocomputed at creation time - */ - public final boolean crit, pub, safe; + /** + * Chunk-id: 4 letters + */ + public final String id; + /** + * Autocomputed at creation time + */ + public final boolean crit, pub, safe; - protected final ImageInfo imgInfo; + protected final ImageInfo imgInfo; - protected ChunkRaw raw; + protected ChunkRaw raw; - private boolean priority = false; // For writing. Queued chunks with high priority will be written - // as soon as - // possible + private boolean priority = false; // For writing. Queued chunks with high priority will be written + // as soon as + // possible - protected int chunkGroup = -1; // chunk group where it was read or writen + protected int chunkGroup = -1; // chunk group where it was read or writen - /** - * Possible ordering constraint for a PngChunk type -only relevant for ancillary chunks. Theoretically, there could be - * more general constraints, but these cover the constraints for standard chunks. - */ - public enum ChunkOrderingConstraint { - /** - * no ordering constraint - */ - NONE, - /** - * Must go before PLTE (and hence, also before IDAT) - */ - BEFORE_PLTE_AND_IDAT, - /** - * Must go after PLTE (if exists) but before IDAT - */ - AFTER_PLTE_BEFORE_IDAT, - /** - * Must go after PLTE (and it must exist) but before IDAT - */ - AFTER_PLTE_BEFORE_IDAT_PLTE_REQUIRED, - /** - * Must before IDAT (before or after PLTE) - */ - BEFORE_IDAT, - /** - * After IDAT (this restriction does not apply to the standard PNG chunks) - */ - AFTER_IDAT, - /** - * Does not apply - */ - NA; + /** + * Possible ordering constraint for a PngChunk type -only relevant for + * ancillary chunks. Theoretically, there could be + * more general constraints, but these cover the constraints for standard + * chunks. + */ + public enum ChunkOrderingConstraint { + /** + * no ordering constraint + */ + NONE, + /** + * Must go before PLTE (and hence, also before IDAT) + */ + BEFORE_PLTE_AND_IDAT, + /** + * Must go after PLTE (if exists) but before IDAT + */ + AFTER_PLTE_BEFORE_IDAT, + /** + * Must go after PLTE (and it must exist) but before IDAT + */ + AFTER_PLTE_BEFORE_IDAT_PLTE_REQUIRED, + /** + * Must before IDAT (before or after PLTE) + */ + BEFORE_IDAT, + /** + * After IDAT (this restriction does not apply to the standard PNG + * chunks) + */ + AFTER_IDAT, + /** + * Does not apply + */ + NA; - public boolean mustGoBeforePLTE() { - return this == BEFORE_PLTE_AND_IDAT; - } + public boolean mustGoBeforePLTE() { + return this == BEFORE_PLTE_AND_IDAT; + } - public boolean mustGoBeforeIDAT() { - return this == BEFORE_IDAT || this == BEFORE_PLTE_AND_IDAT || this == AFTER_PLTE_BEFORE_IDAT; - } + public boolean mustGoBeforeIDAT() { + return this == BEFORE_IDAT || this == BEFORE_PLTE_AND_IDAT || this == AFTER_PLTE_BEFORE_IDAT; + } - /** - * after pallete, if exists - */ - public boolean mustGoAfterPLTE() { - return this == AFTER_PLTE_BEFORE_IDAT || this == AFTER_PLTE_BEFORE_IDAT_PLTE_REQUIRED; - } + /** + * after pallete, if exists + */ + public boolean mustGoAfterPLTE() { + return this == AFTER_PLTE_BEFORE_IDAT || this == AFTER_PLTE_BEFORE_IDAT_PLTE_REQUIRED; + } - public boolean mustGoAfterIDAT() { - return this == AFTER_IDAT; - } + public boolean mustGoAfterIDAT() { + return this == AFTER_IDAT; + } - public boolean isOk(int currentChunkGroup, boolean hasplte) { - if (this == NONE) - return true; - else if (this == BEFORE_IDAT) - return currentChunkGroup < ChunksList.CHUNK_GROUP_4_IDAT; - else if (this == BEFORE_PLTE_AND_IDAT) - return currentChunkGroup < ChunksList.CHUNK_GROUP_2_PLTE; - else if (this == AFTER_PLTE_BEFORE_IDAT) - return hasplte ? currentChunkGroup < ChunksList.CHUNK_GROUP_4_IDAT - : (currentChunkGroup < ChunksList.CHUNK_GROUP_4_IDAT && currentChunkGroup > ChunksList.CHUNK_GROUP_2_PLTE); - else if (this == AFTER_IDAT) - return currentChunkGroup > ChunksList.CHUNK_GROUP_4_IDAT; - return false; - } - } + public boolean isOk(final int currentChunkGroup, final boolean hasplte) { + if (this == NONE) + return true; + else if (this == BEFORE_IDAT) + return currentChunkGroup < ChunksList.CHUNK_GROUP_4_IDAT; + else if (this == BEFORE_PLTE_AND_IDAT) + return currentChunkGroup < ChunksList.CHUNK_GROUP_2_PLTE; + else if (this == AFTER_PLTE_BEFORE_IDAT) + return hasplte ? currentChunkGroup < ChunksList.CHUNK_GROUP_4_IDAT : currentChunkGroup < ChunksList.CHUNK_GROUP_4_IDAT && currentChunkGroup > ChunksList.CHUNK_GROUP_2_PLTE; + else if (this == AFTER_IDAT) + return currentChunkGroup > ChunksList.CHUNK_GROUP_4_IDAT; + return false; + } + } - public PngChunk(String id, ImageInfo imgInfo) { - this.id = id; - this.imgInfo = imgInfo; - this.crit = ChunkHelper.isCritical(id); - this.pub = ChunkHelper.isPublic(id); - this.safe = ChunkHelper.isSafeToCopy(id); - } + public PngChunk(final String id, final ImageInfo imgInfo) { + this.id = id; + this.imgInfo = imgInfo; + crit = ChunkHelper.isCritical(id); + pub = ChunkHelper.isPublic(id); + safe = ChunkHelper.isSafeToCopy(id); + } - protected final ChunkRaw createEmptyChunk(int len, boolean alloc) { - ChunkRaw c = new ChunkRaw(len, ChunkHelper.toBytes(id), alloc); - return c; - } + protected final ChunkRaw createEmptyChunk(final int len, final boolean alloc) { + final ChunkRaw c = new ChunkRaw(len, ChunkHelper.toBytes(id), alloc); + return c; + } - /** - * In which "chunkGroup" (see {@link ChunksList}for definition) this chunks instance was read or written. - *

- * -1 if not read or written (eg, queued) - */ - final public int getChunkGroup() { - return chunkGroup; - } + /** + * In which "chunkGroup" (see {@link ChunksList}for definition) this chunks + * instance was read or written. + *

+ * -1 if not read or written (eg, queued) + */ + final public int getChunkGroup() { + return chunkGroup; + } - /** - * @see #getChunkGroup() - */ - final void setChunkGroup(int chunkGroup) { - this.chunkGroup = chunkGroup; - } + /** + * @see #getChunkGroup() + */ + final void setChunkGroup(final int chunkGroup) { + this.chunkGroup = chunkGroup; + } - public boolean hasPriority() { - return priority; - } + public boolean hasPriority() { + return priority; + } - public void setPriority(boolean priority) { - this.priority = priority; - } + public void setPriority(final boolean priority) { + this.priority = priority; + } - final void write(OutputStream os) { - if (raw == null || raw.data == null) - raw = createRawChunk(); - if (raw == null) - throw new PngjExceptionInternal("null chunk ! creation failed for " + this); - raw.writeChunk(os); - } + final void write(final OutputStream os) { + if (raw == null || raw.data == null) + raw = createRawChunk(); + if (raw == null) + throw new PngjExceptionInternal("null chunk ! creation failed for " + this); + raw.writeChunk(os); + } - /** - * Creates the physical chunk. This is used when writing (serialization). Each particular chunk class implements its - * own logic. - * - * @return A newly allocated and filled raw chunk - */ - public abstract ChunkRaw createRawChunk(); + /** + * Creates the physical chunk. This is used when writing (serialization). + * Each particular chunk class implements its + * own logic. + * + * @return A newly allocated and filled raw chunk + */ + public abstract ChunkRaw createRawChunk(); - /** - * Parses raw chunk and fill inside data. This is used when reading (deserialization). Each particular chunk class - * implements its own logic. - */ - protected abstract void parseFromRaw(ChunkRaw c); + /** + * Parses raw chunk and fill inside data. This is used when reading + * (deserialization). Each particular chunk class + * implements its own logic. + */ + protected abstract void parseFromRaw(ChunkRaw c); - /** - * See {@link PngChunkMultiple} and {@link PngChunkSingle} - * - * @return true if PNG accepts multiple chunks of this class - */ - protected abstract boolean allowsMultiple(); + /** + * See {@link PngChunkMultiple} and {@link PngChunkSingle} + * + * @return true if PNG accepts multiple chunks of this class + */ + protected abstract boolean allowsMultiple(); - public ChunkRaw getRaw() { - return raw; - } + public ChunkRaw getRaw() { + return raw; + } - void setRaw(ChunkRaw raw) { - this.raw = raw; - } + void setRaw(final ChunkRaw raw) { + this.raw = raw; + } - /** - * @see ChunkRaw#len - */ - public int getLen() { - return raw != null ? raw.len : -1; - } + /** + * @see ChunkRaw#len + */ + public int getLen() { + return raw != null ? raw.len : -1; + } - /** - * @see ChunkRaw#getOffset() - */ - public long getOffset() { - return raw != null ? raw.getOffset() : -1; - } + /** + * @see ChunkRaw#getOffset() + */ + public long getOffset() { + return raw != null ? raw.getOffset() : -1; + } - /** - * This signals that the raw chunk (serialized data) as invalid, so that it's regenerated on write. This should be - * called for the (infrequent) case of chunks that were copied from a PngReader and we want to manually modify it. - */ - public void invalidateRawData() { - raw = null; - } + /** + * This signals that the raw chunk (serialized data) as invalid, so that + * it's regenerated on write. This should be + * called for the (infrequent) case of chunks that were copied from a + * PngReader and we want to manually modify it. + */ + public void invalidateRawData() { + raw = null; + } - /** - * see {@link ChunkOrderingConstraint} - */ - public abstract ChunkOrderingConstraint getOrderingConstraint(); + /** + * see {@link ChunkOrderingConstraint} + */ + public abstract ChunkOrderingConstraint getOrderingConstraint(); - @Override - public String toString() { - return "chunk id= " + id + " (len=" + getLen() + " offset=" + getOffset() + ")"; - } + @Override + public String toString() { + return "chunk id= " + id + " (len=" + getLen() + " offset=" + getOffset() + ")"; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkACTL.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkACTL.java index de08207b..3d179f06 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkACTL.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkACTL.java @@ -6,54 +6,52 @@ import ar.com.hjg.pngj.PngHelperInternal; /** * acTL chunk. For APGN, not PGN standard *

- * see https://wiki.mozilla.org/APNG_Specification#.60acTL.60:_The_Animation_Control_Chunk + * see + * https://wiki.mozilla.org/APNG_Specification#.60acTL.60:_The_Animation_Control_Chunk *

*/ public class PngChunkACTL extends PngChunkSingle { - public final static String ID = "acTL"; - private int numFrames; - private int numPlays; + public final static String ID = "acTL"; + private int numFrames; + private int numPlays; + public PngChunkACTL(final ImageInfo info) { + super(PngChunkACTL.ID, info); + } - public PngChunkACTL(ImageInfo info) { - super(ID, info); - } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.BEFORE_IDAT; + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.BEFORE_IDAT; - } + @Override + public ChunkRaw createRawChunk() { + final ChunkRaw c = createEmptyChunk(8, true); + PngHelperInternal.writeInt4tobytes(numFrames, c.data, 0); + PngHelperInternal.writeInt4tobytes(numPlays, c.data, 4); + return c; + } - @Override - public ChunkRaw createRawChunk() { - ChunkRaw c = createEmptyChunk(8, true); - PngHelperInternal.writeInt4tobytes((int) numFrames, c.data, 0); - PngHelperInternal.writeInt4tobytes((int) numPlays, c.data, 4); - return c; - } + @Override + public void parseFromRaw(final ChunkRaw chunk) { + numFrames = PngHelperInternal.readInt4fromBytes(chunk.data, 0); + numPlays = PngHelperInternal.readInt4fromBytes(chunk.data, 4); + } - @Override - public void parseFromRaw(ChunkRaw chunk) { - numFrames = PngHelperInternal.readInt4fromBytes(chunk.data, 0); - numPlays = PngHelperInternal.readInt4fromBytes(chunk.data, 4); - } + public int getNumFrames() { + return numFrames; + } - public int getNumFrames() { - return numFrames; - } - - public void setNumFrames(int numFrames) { - this.numFrames = numFrames; - } - - public int getNumPlays() { - return numPlays; - } - - public void setNumPlays(int numPlays) { - this.numPlays = numPlays; - } + public void setNumFrames(final int numFrames) { + this.numFrames = numFrames; + } + public int getNumPlays() { + return numPlays; + } + public void setNumPlays(final int numPlays) { + this.numPlays = numPlays; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkBKGD.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkBKGD.java index 5ef2b305..6486c189 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkBKGD.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkBKGD.java @@ -12,101 +12,101 @@ import ar.com.hjg.pngj.PngjException; * This chunk structure depends on the image type */ public class PngChunkBKGD extends PngChunkSingle { - public final static String ID = ChunkHelper.bKGD; - // only one of these is meaningful - private int gray; - private int red, green, blue; - private int paletteIndex; + public final static String ID = ChunkHelper.bKGD; + // only one of these is meaningful + private int gray; + private int red, green, blue; + private int paletteIndex; - public PngChunkBKGD(ImageInfo info) { - super(ChunkHelper.bKGD, info); - } + public PngChunkBKGD(final ImageInfo info) { + super(ChunkHelper.bKGD, info); + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.AFTER_PLTE_BEFORE_IDAT; - } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.AFTER_PLTE_BEFORE_IDAT; + } - @Override - public ChunkRaw createRawChunk() { - ChunkRaw c = null; - if (imgInfo.greyscale) { - c = createEmptyChunk(2, true); - PngHelperInternal.writeInt2tobytes(gray, c.data, 0); - } else if (imgInfo.indexed) { - c = createEmptyChunk(1, true); - c.data[0] = (byte) paletteIndex; - } else { - c = createEmptyChunk(6, true); - PngHelperInternal.writeInt2tobytes(red, c.data, 0); - PngHelperInternal.writeInt2tobytes(green, c.data, 0); - PngHelperInternal.writeInt2tobytes(blue, c.data, 0); - } - return c; - } + @Override + public ChunkRaw createRawChunk() { + ChunkRaw c = null; + if (imgInfo.greyscale) { + c = createEmptyChunk(2, true); + PngHelperInternal.writeInt2tobytes(gray, c.data, 0); + } else if (imgInfo.indexed) { + c = createEmptyChunk(1, true); + c.data[0] = (byte) paletteIndex; + } else { + c = createEmptyChunk(6, true); + PngHelperInternal.writeInt2tobytes(red, c.data, 0); + PngHelperInternal.writeInt2tobytes(green, c.data, 0); + PngHelperInternal.writeInt2tobytes(blue, c.data, 0); + } + return c; + } - @Override - public void parseFromRaw(ChunkRaw c) { - if (imgInfo.greyscale) { - gray = PngHelperInternal.readInt2fromBytes(c.data, 0); - } else if (imgInfo.indexed) { - paletteIndex = (int) (c.data[0] & 0xff); - } else { - red = PngHelperInternal.readInt2fromBytes(c.data, 0); - green = PngHelperInternal.readInt2fromBytes(c.data, 2); - blue = PngHelperInternal.readInt2fromBytes(c.data, 4); - } - } + @Override + public void parseFromRaw(final ChunkRaw c) { + if (imgInfo.greyscale) + gray = PngHelperInternal.readInt2fromBytes(c.data, 0); + else if (imgInfo.indexed) + paletteIndex = c.data[0] & 0xff; + else { + red = PngHelperInternal.readInt2fromBytes(c.data, 0); + green = PngHelperInternal.readInt2fromBytes(c.data, 2); + blue = PngHelperInternal.readInt2fromBytes(c.data, 4); + } + } - /** - * Set gray value (0-255 if bitdept=8) - * - * @param gray - */ - public void setGray(int gray) { - if (!imgInfo.greyscale) - throw new PngjException("only gray images support this"); - this.gray = gray; - } + /** + * Set gray value (0-255 if bitdept=8) + * + * @param gray + */ + public void setGray(final int gray) { + if (!imgInfo.greyscale) + throw new PngjException("only gray images support this"); + this.gray = gray; + } - public int getGray() { - if (!imgInfo.greyscale) - throw new PngjException("only gray images support this"); - return gray; - } + public int getGray() { + if (!imgInfo.greyscale) + throw new PngjException("only gray images support this"); + return gray; + } - /** - * Set pallette index - * - */ - public void setPaletteIndex(int i) { - if (!imgInfo.indexed) - throw new PngjException("only indexed (pallete) images support this"); - this.paletteIndex = i; - } + /** + * Set pallette index + * + */ + public void setPaletteIndex(final int i) { + if (!imgInfo.indexed) + throw new PngjException("only indexed (pallete) images support this"); + paletteIndex = i; + } - public int getPaletteIndex() { - if (!imgInfo.indexed) - throw new PngjException("only indexed (pallete) images support this"); - return paletteIndex; - } + public int getPaletteIndex() { + if (!imgInfo.indexed) + throw new PngjException("only indexed (pallete) images support this"); + return paletteIndex; + } - /** - * Set rgb values - * - */ - public void setRGB(int r, int g, int b) { - if (imgInfo.greyscale || imgInfo.indexed) - throw new PngjException("only rgb or rgba images support this"); - red = r; - green = g; - blue = b; - } + /** + * Set rgb values + * + */ + public void setRGB(final int r, final int g, final int b) { + if (imgInfo.greyscale || imgInfo.indexed) + throw new PngjException("only rgb or rgba images support this"); + red = r; + green = g; + blue = b; + } - public int[] getRGB() { - if (imgInfo.greyscale || imgInfo.indexed) - throw new PngjException("only rgb or rgba images support this"); - return new int[] {red, green, blue}; - } + public int[] getRGB() { + if (imgInfo.greyscale || imgInfo.indexed) + throw new PngjException("only rgb or rgba images support this"); + return new int[] { red, green, blue }; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkCHRM.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkCHRM.java index f1b28fdc..6086a7a2 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkCHRM.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkCHRM.java @@ -10,66 +10,66 @@ import ar.com.hjg.pngj.PngjException; * see http://www.w3.org/TR/PNG/#11cHRM */ public class PngChunkCHRM extends PngChunkSingle { - public final static String ID = ChunkHelper.cHRM; + public final static String ID = ChunkHelper.cHRM; - // http://www.w3.org/TR/PNG/#11cHRM - private double whitex, whitey; - private double redx, redy; - private double greenx, greeny; - private double bluex, bluey; + // http://www.w3.org/TR/PNG/#11cHRM + private double whitex, whitey; + private double redx, redy; + private double greenx, greeny; + private double bluex, bluey; - public PngChunkCHRM(ImageInfo info) { - super(ID, info); - } + public PngChunkCHRM(final ImageInfo info) { + super(PngChunkCHRM.ID, info); + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.AFTER_PLTE_BEFORE_IDAT; - } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.AFTER_PLTE_BEFORE_IDAT; + } - @Override - public ChunkRaw createRawChunk() { - ChunkRaw c = null; - c = createEmptyChunk(32, true); - PngHelperInternal.writeInt4tobytes(PngHelperInternal.doubleToInt100000(whitex), c.data, 0); - PngHelperInternal.writeInt4tobytes(PngHelperInternal.doubleToInt100000(whitey), c.data, 4); - PngHelperInternal.writeInt4tobytes(PngHelperInternal.doubleToInt100000(redx), c.data, 8); - PngHelperInternal.writeInt4tobytes(PngHelperInternal.doubleToInt100000(redy), c.data, 12); - PngHelperInternal.writeInt4tobytes(PngHelperInternal.doubleToInt100000(greenx), c.data, 16); - PngHelperInternal.writeInt4tobytes(PngHelperInternal.doubleToInt100000(greeny), c.data, 20); - PngHelperInternal.writeInt4tobytes(PngHelperInternal.doubleToInt100000(bluex), c.data, 24); - PngHelperInternal.writeInt4tobytes(PngHelperInternal.doubleToInt100000(bluey), c.data, 28); - return c; - } + @Override + public ChunkRaw createRawChunk() { + ChunkRaw c = null; + c = createEmptyChunk(32, true); + PngHelperInternal.writeInt4tobytes(PngHelperInternal.doubleToInt100000(whitex), c.data, 0); + PngHelperInternal.writeInt4tobytes(PngHelperInternal.doubleToInt100000(whitey), c.data, 4); + PngHelperInternal.writeInt4tobytes(PngHelperInternal.doubleToInt100000(redx), c.data, 8); + PngHelperInternal.writeInt4tobytes(PngHelperInternal.doubleToInt100000(redy), c.data, 12); + PngHelperInternal.writeInt4tobytes(PngHelperInternal.doubleToInt100000(greenx), c.data, 16); + PngHelperInternal.writeInt4tobytes(PngHelperInternal.doubleToInt100000(greeny), c.data, 20); + PngHelperInternal.writeInt4tobytes(PngHelperInternal.doubleToInt100000(bluex), c.data, 24); + PngHelperInternal.writeInt4tobytes(PngHelperInternal.doubleToInt100000(bluey), c.data, 28); + return c; + } - @Override - public void parseFromRaw(ChunkRaw c) { - if (c.len != 32) - throw new PngjException("bad chunk " + c); - whitex = PngHelperInternal.intToDouble100000(PngHelperInternal.readInt4fromBytes(c.data, 0)); - whitey = PngHelperInternal.intToDouble100000(PngHelperInternal.readInt4fromBytes(c.data, 4)); - redx = PngHelperInternal.intToDouble100000(PngHelperInternal.readInt4fromBytes(c.data, 8)); - redy = PngHelperInternal.intToDouble100000(PngHelperInternal.readInt4fromBytes(c.data, 12)); - greenx = PngHelperInternal.intToDouble100000(PngHelperInternal.readInt4fromBytes(c.data, 16)); - greeny = PngHelperInternal.intToDouble100000(PngHelperInternal.readInt4fromBytes(c.data, 20)); - bluex = PngHelperInternal.intToDouble100000(PngHelperInternal.readInt4fromBytes(c.data, 24)); - bluey = PngHelperInternal.intToDouble100000(PngHelperInternal.readInt4fromBytes(c.data, 28)); - } + @Override + public void parseFromRaw(final ChunkRaw c) { + if (c.len != 32) + throw new PngjException("bad chunk " + c); + whitex = PngHelperInternal.intToDouble100000(PngHelperInternal.readInt4fromBytes(c.data, 0)); + whitey = PngHelperInternal.intToDouble100000(PngHelperInternal.readInt4fromBytes(c.data, 4)); + redx = PngHelperInternal.intToDouble100000(PngHelperInternal.readInt4fromBytes(c.data, 8)); + redy = PngHelperInternal.intToDouble100000(PngHelperInternal.readInt4fromBytes(c.data, 12)); + greenx = PngHelperInternal.intToDouble100000(PngHelperInternal.readInt4fromBytes(c.data, 16)); + greeny = PngHelperInternal.intToDouble100000(PngHelperInternal.readInt4fromBytes(c.data, 20)); + bluex = PngHelperInternal.intToDouble100000(PngHelperInternal.readInt4fromBytes(c.data, 24)); + bluey = PngHelperInternal.intToDouble100000(PngHelperInternal.readInt4fromBytes(c.data, 28)); + } - public void setChromaticities(double whitex, double whitey, double redx, double redy, - double greenx, double greeny, double bluex, double bluey) { - this.whitex = whitex; - this.redx = redx; - this.greenx = greenx; - this.bluex = bluex; - this.whitey = whitey; - this.redy = redy; - this.greeny = greeny; - this.bluey = bluey; - } + public void setChromaticities(final double whitex, final double whitey, final double redx, final double redy, + final double greenx, final double greeny, final double bluex, final double bluey) { + this.whitex = whitex; + this.redx = redx; + this.greenx = greenx; + this.bluex = bluex; + this.whitey = whitey; + this.redy = redy; + this.greeny = greeny; + this.bluey = bluey; + } - public double[] getChromaticities() { - return new double[] {whitex, whitey, redx, redy, greenx, greeny, bluex, bluey}; - } + public double[] getChromaticities() { + return new double[] { whitex, whitey, redx, redy, greenx, greeny, bluex, bluey }; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkFCTL.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkFCTL.java index f55617cb..4a8c8d1f 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkFCTL.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkFCTL.java @@ -6,153 +6,153 @@ import ar.com.hjg.pngj.PngHelperInternal; /** * fcTL chunk. For APGN, not PGN standard *

- * see https://wiki.mozilla.org/APNG_Specification#.60fcTL.60:_The_Frame_Control_Chunk + * see + * https://wiki.mozilla.org/APNG_Specification#.60fcTL.60:_The_Frame_Control_Chunk *

*/ public class PngChunkFCTL extends PngChunkMultiple { - public final static String ID = "fcTL"; + public final static String ID = "fcTL"; - public final static byte APNG_DISPOSE_OP_NONE = 0; - public final static byte APNG_DISPOSE_OP_BACKGROUND = 1; - public final static byte APNG_DISPOSE_OP_PREVIOUS = 2; - public final static byte APNG_BLEND_OP_SOURCE = 0; - public final static byte APNG_BLEND_OP_OVER = 1; + public final static byte APNG_DISPOSE_OP_NONE = 0; + public final static byte APNG_DISPOSE_OP_BACKGROUND = 1; + public final static byte APNG_DISPOSE_OP_PREVIOUS = 2; + public final static byte APNG_BLEND_OP_SOURCE = 0; + public final static byte APNG_BLEND_OP_OVER = 1; - private int seqNum; - private int width, height, xOff, yOff; - private int delayNum, delayDen; - private byte disposeOp, blendOp; + private int seqNum; + private int width, height, xOff, yOff; + private int delayNum, delayDen; + private byte disposeOp, blendOp; - public PngChunkFCTL(ImageInfo info) { - super(ID, info); - } + public PngChunkFCTL(final ImageInfo info) { + super(PngChunkFCTL.ID, info); + } - public ImageInfo getEquivImageInfo() { - return new ImageInfo(width, height, imgInfo.bitDepth, imgInfo.alpha, imgInfo.greyscale, - imgInfo.indexed); - } + public ImageInfo getEquivImageInfo() { + return new ImageInfo(width, height, imgInfo.bitDepth, imgInfo.alpha, imgInfo.greyscale, imgInfo.indexed); + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.NONE; - } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.NONE; + } - @Override - public ChunkRaw createRawChunk() { - ChunkRaw c = createEmptyChunk(8, true); - int off = 0; - PngHelperInternal.writeInt4tobytes(seqNum, c.data, off); - off += 4; - PngHelperInternal.writeInt4tobytes(width, c.data, off); - off += 4; - PngHelperInternal.writeInt4tobytes(height, c.data, off); - off += 4; - PngHelperInternal.writeInt4tobytes(xOff, c.data, off); - off += 4; - PngHelperInternal.writeInt4tobytes(yOff, c.data, off); - off += 4; - PngHelperInternal.writeInt2tobytes(delayNum, c.data, off); - off += 2; - PngHelperInternal.writeInt2tobytes(delayDen, c.data, off); - off += 2; - c.data[off] = disposeOp; - off += 1; - c.data[off] = blendOp; - return c; - } + @Override + public ChunkRaw createRawChunk() { + final ChunkRaw c = createEmptyChunk(8, true); + int off = 0; + PngHelperInternal.writeInt4tobytes(seqNum, c.data, off); + off += 4; + PngHelperInternal.writeInt4tobytes(width, c.data, off); + off += 4; + PngHelperInternal.writeInt4tobytes(height, c.data, off); + off += 4; + PngHelperInternal.writeInt4tobytes(xOff, c.data, off); + off += 4; + PngHelperInternal.writeInt4tobytes(yOff, c.data, off); + off += 4; + PngHelperInternal.writeInt2tobytes(delayNum, c.data, off); + off += 2; + PngHelperInternal.writeInt2tobytes(delayDen, c.data, off); + off += 2; + c.data[off] = disposeOp; + off += 1; + c.data[off] = blendOp; + return c; + } - @Override - public void parseFromRaw(ChunkRaw chunk) { - int off = 0; - seqNum = PngHelperInternal.readInt4fromBytes(chunk.data, off); - off += 4; - width = PngHelperInternal.readInt4fromBytes(chunk.data, off); - off += 4; - height = PngHelperInternal.readInt4fromBytes(chunk.data, off); - off += 4; - xOff = PngHelperInternal.readInt4fromBytes(chunk.data, off); - off += 4; - yOff = PngHelperInternal.readInt4fromBytes(chunk.data, off); - off += 4; - delayNum = PngHelperInternal.readInt2fromBytes(chunk.data, off); - off += 2; - delayDen = PngHelperInternal.readInt2fromBytes(chunk.data, off); - off += 2; - disposeOp = chunk.data[off]; - off += 1; - blendOp = chunk.data[off]; - } + @Override + public void parseFromRaw(final ChunkRaw chunk) { + int off = 0; + seqNum = PngHelperInternal.readInt4fromBytes(chunk.data, off); + off += 4; + width = PngHelperInternal.readInt4fromBytes(chunk.data, off); + off += 4; + height = PngHelperInternal.readInt4fromBytes(chunk.data, off); + off += 4; + xOff = PngHelperInternal.readInt4fromBytes(chunk.data, off); + off += 4; + yOff = PngHelperInternal.readInt4fromBytes(chunk.data, off); + off += 4; + delayNum = PngHelperInternal.readInt2fromBytes(chunk.data, off); + off += 2; + delayDen = PngHelperInternal.readInt2fromBytes(chunk.data, off); + off += 2; + disposeOp = chunk.data[off]; + off += 1; + blendOp = chunk.data[off]; + } - public int getSeqNum() { - return seqNum; - } + public int getSeqNum() { + return seqNum; + } - public void setSeqNum(int seqNum) { - this.seqNum = seqNum; - } + public void setSeqNum(final int seqNum) { + this.seqNum = seqNum; + } - public int getWidth() { - return width; - } + public int getWidth() { + return width; + } - public void setWidth(int width) { - this.width = width; - } + public void setWidth(final int width) { + this.width = width; + } - public int getHeight() { - return height; - } + public int getHeight() { + return height; + } - public void setHeight(int height) { - this.height = height; - } + public void setHeight(final int height) { + this.height = height; + } - public int getxOff() { - return xOff; - } + public int getxOff() { + return xOff; + } - public void setxOff(int xOff) { - this.xOff = xOff; - } + public void setxOff(final int xOff) { + this.xOff = xOff; + } - public int getyOff() { - return yOff; - } + public int getyOff() { + return yOff; + } - public void setyOff(int yOff) { - this.yOff = yOff; - } + public void setyOff(final int yOff) { + this.yOff = yOff; + } - public int getDelayNum() { - return delayNum; - } + public int getDelayNum() { + return delayNum; + } - public void setDelayNum(int delayNum) { - this.delayNum = delayNum; - } + public void setDelayNum(final int delayNum) { + this.delayNum = delayNum; + } - public int getDelayDen() { - return delayDen; - } + public int getDelayDen() { + return delayDen; + } - public void setDelayDen(int delayDen) { - this.delayDen = delayDen; - } + public void setDelayDen(final int delayDen) { + this.delayDen = delayDen; + } - public byte getDisposeOp() { - return disposeOp; - } + public byte getDisposeOp() { + return disposeOp; + } - public void setDisposeOp(byte disposeOp) { - this.disposeOp = disposeOp; - } + public void setDisposeOp(final byte disposeOp) { + this.disposeOp = disposeOp; + } - public byte getBlendOp() { - return blendOp; - } + public byte getBlendOp() { + return blendOp; + } - public void setBlendOp(byte blendOp) { - this.blendOp = blendOp; - } + public void setBlendOp(final byte blendOp) { + this.blendOp = blendOp; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkFDAT.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkFDAT.java index 16ecc7ad..47449a00 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkFDAT.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkFDAT.java @@ -7,64 +7,66 @@ import ar.com.hjg.pngj.PngjException; /** * fdAT chunk. For APGN, not PGN standard *

- * see https://wiki.mozilla.org/APNG_Specification#.60fdAT.60:_The_Frame_Data_Chunk + * see + * https://wiki.mozilla.org/APNG_Specification#.60fdAT.60:_The_Frame_Data_Chunk *

- * This implementation does not support buffering, this should be not managed similar to a IDAT chunk - * + * This implementation does not support buffering, this should be not managed + * similar to a IDAT chunk + * */ public class PngChunkFDAT extends PngChunkMultiple { - public final static String ID = "fdAT"; - private int seqNum; - private byte[] buffer; // normally not allocated - if so, it's the raw data, so it includes the 4bytes seqNum - int datalen; // length of idat data, excluding seqNUm (= chunk.len-4) + public final static String ID = "fdAT"; + private int seqNum; + private byte[] buffer; // normally not allocated - if so, it's the raw data, so it includes the 4bytes seqNum + int datalen; // length of idat data, excluding seqNUm (= chunk.len-4) - public PngChunkFDAT(ImageInfo info) { - super(ID, info); - } + public PngChunkFDAT(final ImageInfo info) { + super(PngChunkFDAT.ID, info); + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.AFTER_IDAT; - } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.AFTER_IDAT; + } - @Override - public ChunkRaw createRawChunk() { - if (buffer == null) - throw new PngjException("not buffered"); - ChunkRaw c = createEmptyChunk(datalen + 4, false); - c.data = buffer; // shallow copy! - return c; - } + @Override + public ChunkRaw createRawChunk() { + if (buffer == null) + throw new PngjException("not buffered"); + final ChunkRaw c = createEmptyChunk(datalen + 4, false); + c.data = buffer; // shallow copy! + return c; + } - @Override - public void parseFromRaw(ChunkRaw chunk) { - seqNum = PngHelperInternal.readInt4fromBytes(chunk.data, 0); - datalen = chunk.len - 4; - buffer = chunk.data; - } + @Override + public void parseFromRaw(final ChunkRaw chunk) { + seqNum = PngHelperInternal.readInt4fromBytes(chunk.data, 0); + datalen = chunk.len - 4; + buffer = chunk.data; + } - public int getSeqNum() { - return seqNum; - } + public int getSeqNum() { + return seqNum; + } - public void setSeqNum(int seqNum) { - this.seqNum = seqNum; - } + public void setSeqNum(final int seqNum) { + this.seqNum = seqNum; + } - public byte[] getBuffer() { - return buffer; - } + public byte[] getBuffer() { + return buffer; + } - public void setBuffer(byte[] buffer) { - this.buffer = buffer; - } + public void setBuffer(final byte[] buffer) { + this.buffer = buffer; + } - public int getDatalen() { - return datalen; - } + public int getDatalen() { + return datalen; + } - public void setDatalen(int datalen) { - this.datalen = datalen; - } + public void setDatalen(final int datalen) { + this.datalen = datalen; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkGAMA.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkGAMA.java index d1920c88..3b70654b 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkGAMA.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkGAMA.java @@ -10,42 +10,42 @@ import ar.com.hjg.pngj.PngjException; * see http://www.w3.org/TR/PNG/#11gAMA */ public class PngChunkGAMA extends PngChunkSingle { - public final static String ID = ChunkHelper.gAMA; + public final static String ID = ChunkHelper.gAMA; - // http://www.w3.org/TR/PNG/#11gAMA - private double gamma; + // http://www.w3.org/TR/PNG/#11gAMA + private double gamma; - public PngChunkGAMA(ImageInfo info) { - super(ID, info); - } + public PngChunkGAMA(final ImageInfo info) { + super(PngChunkGAMA.ID, info); + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.BEFORE_PLTE_AND_IDAT; - } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.BEFORE_PLTE_AND_IDAT; + } - @Override - public ChunkRaw createRawChunk() { - ChunkRaw c = createEmptyChunk(4, true); - int g = (int) (gamma * 100000 + 0.5); - PngHelperInternal.writeInt4tobytes(g, c.data, 0); - return c; - } + @Override + public ChunkRaw createRawChunk() { + final ChunkRaw c = createEmptyChunk(4, true); + final int g = (int) (gamma * 100000 + 0.5); + PngHelperInternal.writeInt4tobytes(g, c.data, 0); + return c; + } - @Override - public void parseFromRaw(ChunkRaw chunk) { - if (chunk.len != 4) - throw new PngjException("bad chunk " + chunk); - int g = PngHelperInternal.readInt4fromBytes(chunk.data, 0); - gamma = ((double) g) / 100000.0; - } + @Override + public void parseFromRaw(final ChunkRaw chunk) { + if (chunk.len != 4) + throw new PngjException("bad chunk " + chunk); + final int g = PngHelperInternal.readInt4fromBytes(chunk.data, 0); + gamma = g / 100000.0; + } - public double getGamma() { - return gamma; - } + public double getGamma() { + return gamma; + } - public void setGamma(double gamma) { - this.gamma = gamma; - } + public void setGamma(final double gamma) { + this.gamma = gamma; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkHIST.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkHIST.java index ebdf2355..7d84aed8 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkHIST.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkHIST.java @@ -11,48 +11,46 @@ import ar.com.hjg.pngj.PngjException; * only for palette images */ public class PngChunkHIST extends PngChunkSingle { - public final static String ID = ChunkHelper.hIST; + public final static String ID = ChunkHelper.hIST; - private int[] hist = new int[0]; // should have same lenght as palette + private int[] hist = new int[0]; // should have same lenght as palette - public PngChunkHIST(ImageInfo info) { - super(ID, info); - } + public PngChunkHIST(final ImageInfo info) { + super(PngChunkHIST.ID, info); + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.AFTER_PLTE_BEFORE_IDAT; - } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.AFTER_PLTE_BEFORE_IDAT; + } - @Override - public void parseFromRaw(ChunkRaw c) { - if (!imgInfo.indexed) - throw new PngjException("only indexed images accept a HIST chunk"); - int nentries = c.data.length / 2; - hist = new int[nentries]; - for (int i = 0; i < hist.length; i++) { - hist[i] = PngHelperInternal.readInt2fromBytes(c.data, i * 2); - } - } + @Override + public void parseFromRaw(final ChunkRaw c) { + if (!imgInfo.indexed) + throw new PngjException("only indexed images accept a HIST chunk"); + final int nentries = c.data.length / 2; + hist = new int[nentries]; + for (int i = 0; i < hist.length; i++) + hist[i] = PngHelperInternal.readInt2fromBytes(c.data, i * 2); + } - @Override - public ChunkRaw createRawChunk() { - if (!imgInfo.indexed) - throw new PngjException("only indexed images accept a HIST chunk"); - ChunkRaw c = null; - c = createEmptyChunk(hist.length * 2, true); - for (int i = 0; i < hist.length; i++) { - PngHelperInternal.writeInt2tobytes(hist[i], c.data, i * 2); - } - return c; - } + @Override + public ChunkRaw createRawChunk() { + if (!imgInfo.indexed) + throw new PngjException("only indexed images accept a HIST chunk"); + ChunkRaw c = null; + c = createEmptyChunk(hist.length * 2, true); + for (int i = 0; i < hist.length; i++) + PngHelperInternal.writeInt2tobytes(hist[i], c.data, i * 2); + return c; + } - public int[] getHist() { - return hist; - } + public int[] getHist() { + return hist; + } - public void setHist(int[] hist) { - this.hist = hist; - } + public void setHist(final int[] hist) { + this.hist = hist; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkICCP.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkICCP.java index b3b1109f..caa2de2a 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkICCP.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkICCP.java @@ -9,69 +9,68 @@ import ar.com.hjg.pngj.PngjException; * See {@link http://www.w3.org/TR/PNG/#11iCCP} */ public class PngChunkICCP extends PngChunkSingle { - public final static String ID = ChunkHelper.iCCP; + public final static String ID = ChunkHelper.iCCP; - // http://www.w3.org/TR/PNG/#11iCCP - private String profileName; - private byte[] compressedProfile; // copmression/decopmresion is done in getter/setter + // http://www.w3.org/TR/PNG/#11iCCP + private String profileName; + private byte[] compressedProfile; // copmression/decopmresion is done in getter/setter - public PngChunkICCP(ImageInfo info) { - super(ID, info); - } + public PngChunkICCP(final ImageInfo info) { + super(PngChunkICCP.ID, info); + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.BEFORE_PLTE_AND_IDAT; - } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.BEFORE_PLTE_AND_IDAT; + } - @Override - public ChunkRaw createRawChunk() { - ChunkRaw c = createEmptyChunk(profileName.length() + compressedProfile.length + 2, true); - System.arraycopy(ChunkHelper.toBytes(profileName), 0, c.data, 0, profileName.length()); - c.data[profileName.length()] = 0; - c.data[profileName.length() + 1] = 0; - System.arraycopy(compressedProfile, 0, c.data, profileName.length() + 2, - compressedProfile.length); - return c; - } + @Override + public ChunkRaw createRawChunk() { + final ChunkRaw c = createEmptyChunk(profileName.length() + compressedProfile.length + 2, true); + System.arraycopy(ChunkHelper.toBytes(profileName), 0, c.data, 0, profileName.length()); + c.data[profileName.length()] = 0; + c.data[profileName.length() + 1] = 0; + System.arraycopy(compressedProfile, 0, c.data, profileName.length() + 2, compressedProfile.length); + return c; + } - @Override - public void parseFromRaw(ChunkRaw chunk) { - int pos0 = ChunkHelper.posNullByte(chunk.data); - profileName = ChunkHelper.toString(chunk.data, 0, pos0); - int comp = (chunk.data[pos0 + 1] & 0xff); - if (comp != 0) - throw new PngjException("bad compression for ChunkTypeICCP"); - int compdatasize = chunk.data.length - (pos0 + 2); - compressedProfile = new byte[compdatasize]; - System.arraycopy(chunk.data, pos0 + 2, compressedProfile, 0, compdatasize); - } + @Override + public void parseFromRaw(final ChunkRaw chunk) { + final int pos0 = ChunkHelper.posNullByte(chunk.data); + profileName = ChunkHelper.toString(chunk.data, 0, pos0); + final int comp = chunk.data[pos0 + 1] & 0xff; + if (comp != 0) + throw new PngjException("bad compression for ChunkTypeICCP"); + final int compdatasize = chunk.data.length - (pos0 + 2); + compressedProfile = new byte[compdatasize]; + System.arraycopy(chunk.data, pos0 + 2, compressedProfile, 0, compdatasize); + } - /** - * The profile should be uncompressed bytes - */ - public void setProfileNameAndContent(String name, byte[] profile) { - profileName = name; - compressedProfile = ChunkHelper.compressBytes(profile, true); - } + /** + * The profile should be uncompressed bytes + */ + public void setProfileNameAndContent(final String name, final byte[] profile) { + profileName = name; + compressedProfile = ChunkHelper.compressBytes(profile, true); + } - public void setProfileNameAndContent(String name, String profile) { - setProfileNameAndContent(name, ChunkHelper.toBytes(profile)); - } + public void setProfileNameAndContent(final String name, final String profile) { + setProfileNameAndContent(name, ChunkHelper.toBytes(profile)); + } - public String getProfileName() { - return profileName; - } + public String getProfileName() { + return profileName; + } - /** - * uncompressed - **/ - public byte[] getProfile() { - return ChunkHelper.compressBytes(compressedProfile, false); - } + /** + * uncompressed + **/ + public byte[] getProfile() { + return ChunkHelper.compressBytes(compressedProfile, false); + } - public String getProfileAsString() { - return ChunkHelper.toString(getProfile()); - } + public String getProfileAsString() { + return ChunkHelper.toString(getProfile()); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkIDAT.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkIDAT.java index 625aefaa..febd1469 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkIDAT.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkIDAT.java @@ -7,28 +7,29 @@ import ar.com.hjg.pngj.ImageInfo; *

* see http://www.w3.org/TR/PNG/#11IDAT *

- * This is dummy placeholder - we write/read this chunk (actually several) by special code. + * This is dummy placeholder - we write/read this chunk (actually several) by + * special code. */ public class PngChunkIDAT extends PngChunkMultiple { - public final static String ID = ChunkHelper.IDAT; + public final static String ID = ChunkHelper.IDAT; - // http://www.w3.org/TR/PNG/#11IDAT - public PngChunkIDAT(ImageInfo i) { - super(ID, i); - } + // http://www.w3.org/TR/PNG/#11IDAT + public PngChunkIDAT(final ImageInfo i) { + super(PngChunkIDAT.ID, i); + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.NA; - } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.NA; + } - @Override - public ChunkRaw createRawChunk() {// does nothing - return null; - } + @Override + public ChunkRaw createRawChunk() {// does nothing + return null; + } - @Override - public void parseFromRaw(ChunkRaw c) { // does nothing - } + @Override + public void parseFromRaw(final ChunkRaw c) { // does nothing + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkIEND.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkIEND.java index 58073d77..01fb6259 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkIEND.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkIEND.java @@ -8,28 +8,28 @@ import ar.com.hjg.pngj.ImageInfo; * see http://www.w3.org/TR/PNG/#11IEND */ public class PngChunkIEND extends PngChunkSingle { - public final static String ID = ChunkHelper.IEND; + public final static String ID = ChunkHelper.IEND; - // http://www.w3.org/TR/PNG/#11IEND - // this is a dummy placeholder - public PngChunkIEND(ImageInfo info) { - super(ID, info); - } + // http://www.w3.org/TR/PNG/#11IEND + // this is a dummy placeholder + public PngChunkIEND(final ImageInfo info) { + super(PngChunkIEND.ID, info); + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.NA; - } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.NA; + } - @Override - public ChunkRaw createRawChunk() { - ChunkRaw c = new ChunkRaw(0, ChunkHelper.b_IEND, false); - return c; - } + @Override + public ChunkRaw createRawChunk() { + final ChunkRaw c = new ChunkRaw(0, ChunkHelper.b_IEND, false); + return c; + } - @Override - public void parseFromRaw(ChunkRaw c) { - // this is not used - } + @Override + public void parseFromRaw(final ChunkRaw c) { + // this is not used + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkIHDR.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkIHDR.java index a2ea517e..ddcbd5ec 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkIHDR.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkIHDR.java @@ -15,171 +15,170 @@ import ar.com.hjg.pngj.PngjInputException; * This is a special critical Chunk. */ public class PngChunkIHDR extends PngChunkSingle { - public final static String ID = ChunkHelper.IHDR; + public final static String ID = ChunkHelper.IHDR; - private int cols; - private int rows; - private int bitspc; - private int colormodel; - private int compmeth; - private int filmeth; - private int interlaced; + private int cols; + private int rows; + private int bitspc; + private int colormodel; + private int compmeth; + private int filmeth; + private int interlaced; - // http://www.w3.org/TR/PNG/#11IHDR - // - public PngChunkIHDR(ImageInfo info) { // argument is normally null here, if not null is used to fill the fields - super(ID, info); - if (info != null) - fillFromInfo(info); - } + // http://www.w3.org/TR/PNG/#11IHDR + // + public PngChunkIHDR(final ImageInfo info) { // argument is normally null here, if not null is used to fill the fields + super(PngChunkIHDR.ID, info); + if (info != null) + fillFromInfo(info); + } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.NA; + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.NA; - } + @Override + public ChunkRaw createRawChunk() { + final ChunkRaw c = new ChunkRaw(13, ChunkHelper.b_IHDR, true); + int offset = 0; + PngHelperInternal.writeInt4tobytes(cols, c.data, offset); + offset += 4; + PngHelperInternal.writeInt4tobytes(rows, c.data, offset); + offset += 4; + c.data[offset++] = (byte) bitspc; + c.data[offset++] = (byte) colormodel; + c.data[offset++] = (byte) compmeth; + c.data[offset++] = (byte) filmeth; + c.data[offset++] = (byte) interlaced; + return c; + } - @Override - public ChunkRaw createRawChunk() { - ChunkRaw c = new ChunkRaw(13, ChunkHelper.b_IHDR, true); - int offset = 0; - PngHelperInternal.writeInt4tobytes(cols, c.data, offset); - offset += 4; - PngHelperInternal.writeInt4tobytes(rows, c.data, offset); - offset += 4; - c.data[offset++] = (byte) bitspc; - c.data[offset++] = (byte) colormodel; - c.data[offset++] = (byte) compmeth; - c.data[offset++] = (byte) filmeth; - c.data[offset++] = (byte) interlaced; - return c; - } + @Override + public void parseFromRaw(final ChunkRaw c) { + if (c.len != 13) + throw new PngjException("Bad IDHR len " + c.len); + final ByteArrayInputStream st = c.getAsByteStream(); + cols = PngHelperInternal.readInt4(st); + rows = PngHelperInternal.readInt4(st); + // bit depth: number of bits per channel + bitspc = PngHelperInternal.readByte(st); + colormodel = PngHelperInternal.readByte(st); + compmeth = PngHelperInternal.readByte(st); + filmeth = PngHelperInternal.readByte(st); + interlaced = PngHelperInternal.readByte(st); + } - @Override - public void parseFromRaw(ChunkRaw c) { - if (c.len != 13) - throw new PngjException("Bad IDHR len " + c.len); - ByteArrayInputStream st = c.getAsByteStream(); - cols = PngHelperInternal.readInt4(st); - rows = PngHelperInternal.readInt4(st); - // bit depth: number of bits per channel - bitspc = PngHelperInternal.readByte(st); - colormodel = PngHelperInternal.readByte(st); - compmeth = PngHelperInternal.readByte(st); - filmeth = PngHelperInternal.readByte(st); - interlaced = PngHelperInternal.readByte(st); - } + public int getCols() { + return cols; + } - public int getCols() { - return cols; - } + public void setCols(final int cols) { + this.cols = cols; + } - public void setCols(int cols) { - this.cols = cols; - } + public int getRows() { + return rows; + } - public int getRows() { - return rows; - } + public void setRows(final int rows) { + this.rows = rows; + } - public void setRows(int rows) { - this.rows = rows; - } + public int getBitspc() { + return bitspc; + } - public int getBitspc() { - return bitspc; - } + public void setBitspc(final int bitspc) { + this.bitspc = bitspc; + } - public void setBitspc(int bitspc) { - this.bitspc = bitspc; - } + public int getColormodel() { + return colormodel; + } - public int getColormodel() { - return colormodel; - } + public void setColormodel(final int colormodel) { + this.colormodel = colormodel; + } - public void setColormodel(int colormodel) { - this.colormodel = colormodel; - } + public int getCompmeth() { + return compmeth; + } - public int getCompmeth() { - return compmeth; - } + public void setCompmeth(final int compmeth) { + this.compmeth = compmeth; + } - public void setCompmeth(int compmeth) { - this.compmeth = compmeth; - } + public int getFilmeth() { + return filmeth; + } - public int getFilmeth() { - return filmeth; - } + public void setFilmeth(final int filmeth) { + this.filmeth = filmeth; + } - public void setFilmeth(int filmeth) { - this.filmeth = filmeth; - } + public int getInterlaced() { + return interlaced; + } - public int getInterlaced() { - return interlaced; - } + public void setInterlaced(final int interlaced) { + this.interlaced = interlaced; + } - public void setInterlaced(int interlaced) { - this.interlaced = interlaced; - } + public boolean isInterlaced() { + return getInterlaced() == 1; + } - public boolean isInterlaced() { - return getInterlaced() == 1; - } + public void fillFromInfo(final ImageInfo info) { + setCols(imgInfo.cols); + setRows(imgInfo.rows); + setBitspc(imgInfo.bitDepth); + int colormodel = 0; + if (imgInfo.alpha) + colormodel += 0x04; + if (imgInfo.indexed) + colormodel += 0x01; + if (!imgInfo.greyscale) + colormodel += 0x02; + setColormodel(colormodel); + setCompmeth(0); // compression method 0=deflate + setFilmeth(0); // filter method (0) + setInterlaced(0); // we never interlace + } - public void fillFromInfo(ImageInfo info) { - setCols(imgInfo.cols); - setRows(imgInfo.rows); - setBitspc(imgInfo.bitDepth); - int colormodel = 0; - if (imgInfo.alpha) - colormodel += 0x04; - if (imgInfo.indexed) - colormodel += 0x01; - if (!imgInfo.greyscale) - colormodel += 0x02; - setColormodel(colormodel); - setCompmeth(0); // compression method 0=deflate - setFilmeth(0); // filter method (0) - setInterlaced(0); // we never interlace - } + /** throws PngInputException if unexpected values */ + public ImageInfo createImageInfo() { + check(); + final boolean alpha = (getColormodel() & 0x04) != 0; + final boolean palette = (getColormodel() & 0x01) != 0; + final boolean grayscale = getColormodel() == 0 || getColormodel() == 4; + // creates ImgInfo and imgLine, and allocates buffers + return new ImageInfo(getCols(), getRows(), getBitspc(), alpha, grayscale, palette); + } - /** throws PngInputException if unexpected values */ - public ImageInfo createImageInfo() { - check(); - boolean alpha = (getColormodel() & 0x04) != 0; - boolean palette = (getColormodel() & 0x01) != 0; - boolean grayscale = (getColormodel() == 0 || getColormodel() == 4); - // creates ImgInfo and imgLine, and allocates buffers - return new ImageInfo(getCols(), getRows(), getBitspc(), alpha, grayscale, palette); - } - - public void check() { - if (cols < 1 || rows < 1 || compmeth != 0 || filmeth != 0) - throw new PngjInputException("bad IHDR: col/row/compmethod/filmethod invalid"); - if (bitspc != 1 && bitspc != 2 && bitspc != 4 && bitspc != 8 && bitspc != 16) - throw new PngjInputException("bad IHDR: bitdepth invalid"); - if (interlaced < 0 || interlaced > 1) - throw new PngjInputException("bad IHDR: interlace invalid"); - switch (colormodel) { - case 0: - break; - case 3: - if (bitspc == 16) - throw new PngjInputException("bad IHDR: bitdepth invalid"); - break; - case 2: - case 4: - case 6: - if (bitspc != 8 && bitspc != 16) - throw new PngjInputException("bad IHDR: bitdepth invalid"); - break; - default: - throw new PngjInputException("bad IHDR: invalid colormodel"); - } - } + public void check() { + if (cols < 1 || rows < 1 || compmeth != 0 || filmeth != 0) + throw new PngjInputException("bad IHDR: col/row/compmethod/filmethod invalid"); + if (bitspc != 1 && bitspc != 2 && bitspc != 4 && bitspc != 8 && bitspc != 16) + throw new PngjInputException("bad IHDR: bitdepth invalid"); + if (interlaced < 0 || interlaced > 1) + throw new PngjInputException("bad IHDR: interlace invalid"); + switch (colormodel) { + case 0: + break; + case 3: + if (bitspc == 16) + throw new PngjInputException("bad IHDR: bitdepth invalid"); + break; + case 2: + case 4: + case 6: + if (bitspc != 8 && bitspc != 16) + throw new PngjInputException("bad IHDR: bitdepth invalid"); + break; + default: + throw new PngjInputException("bad IHDR: invalid colormodel"); + } + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkITXT.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkITXT.java index f24974ac..d9d1bb83 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkITXT.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkITXT.java @@ -12,100 +12,97 @@ import ar.com.hjg.pngj.PngjException; * see http://www.w3.org/TR/PNG/#11iTXt */ public class PngChunkITXT extends PngChunkTextVar { - public final static String ID = ChunkHelper.iTXt; + public final static String ID = ChunkHelper.iTXt; - private boolean compressed = false; - private String langTag = ""; - private String translatedTag = ""; + private boolean compressed = false; + private String langTag = ""; + private String translatedTag = ""; - // http://www.w3.org/TR/PNG/#11iTXt - public PngChunkITXT(ImageInfo info) { - super(ID, info); - } + // http://www.w3.org/TR/PNG/#11iTXt + public PngChunkITXT(final ImageInfo info) { + super(PngChunkITXT.ID, info); + } - @Override - public ChunkRaw createRawChunk() { - if (key == null || key.trim().length() == 0) - throw new PngjException("Text chunk key must be non empty"); - try { - ByteArrayOutputStream ba = new ByteArrayOutputStream(); - ba.write(ChunkHelper.toBytes(key)); - ba.write(0); // separator - ba.write(compressed ? 1 : 0); - ba.write(0); // compression method (always 0) - ba.write(ChunkHelper.toBytes(langTag)); - ba.write(0); // separator - ba.write(ChunkHelper.toBytesUTF8(translatedTag)); - ba.write(0); // separator - byte[] textbytes = ChunkHelper.toBytesUTF8(val); - if (compressed) { - textbytes = ChunkHelper.compressBytes(textbytes, true); - } - ba.write(textbytes); - byte[] b = ba.toByteArray(); - ChunkRaw chunk = createEmptyChunk(b.length, false); - chunk.data = b; - return chunk; - } catch (IOException e) { - throw new PngjException(e); - } - } + @Override + public ChunkRaw createRawChunk() { + if (key == null || key.trim().length() == 0) + throw new PngjException("Text chunk key must be non empty"); + try { + final ByteArrayOutputStream ba = new ByteArrayOutputStream(); + ba.write(ChunkHelper.toBytes(key)); + ba.write(0); // separator + ba.write(compressed ? 1 : 0); + ba.write(0); // compression method (always 0) + ba.write(ChunkHelper.toBytes(langTag)); + ba.write(0); // separator + ba.write(ChunkHelper.toBytesUTF8(translatedTag)); + ba.write(0); // separator + byte[] textbytes = ChunkHelper.toBytesUTF8(val); + if (compressed) + textbytes = ChunkHelper.compressBytes(textbytes, true); + ba.write(textbytes); + final byte[] b = ba.toByteArray(); + final ChunkRaw chunk = createEmptyChunk(b.length, false); + chunk.data = b; + return chunk; + } catch (final IOException e) { + throw new PngjException(e); + } + } - @Override - public void parseFromRaw(ChunkRaw c) { - int nullsFound = 0; - int[] nullsIdx = new int[3]; - for (int i = 0; i < c.data.length; i++) { - if (c.data[i] != 0) - continue; - nullsIdx[nullsFound] = i; - nullsFound++; - if (nullsFound == 1) - i += 2; - if (nullsFound == 3) - break; - } - if (nullsFound != 3) - throw new PngjException("Bad formed PngChunkITXT chunk"); - key = ChunkHelper.toString(c.data, 0, nullsIdx[0]); - int i = nullsIdx[0] + 1; - compressed = c.data[i] == 0 ? false : true; - i++; - if (compressed && c.data[i] != 0) - throw new PngjException("Bad formed PngChunkITXT chunk - bad compression method "); - langTag = ChunkHelper.toString(c.data, i, nullsIdx[1] - i); - translatedTag = - ChunkHelper.toStringUTF8(c.data, nullsIdx[1] + 1, nullsIdx[2] - nullsIdx[1] - 1); - i = nullsIdx[2] + 1; - if (compressed) { - byte[] bytes = ChunkHelper.compressBytes(c.data, i, c.data.length - i, false); - val = ChunkHelper.toStringUTF8(bytes); - } else { - val = ChunkHelper.toStringUTF8(c.data, i, c.data.length - i); - } - } + @Override + public void parseFromRaw(final ChunkRaw c) { + int nullsFound = 0; + final int[] nullsIdx = new int[3]; + for (int i = 0; i < c.data.length; i++) { + if (c.data[i] != 0) + continue; + nullsIdx[nullsFound] = i; + nullsFound++; + if (nullsFound == 1) + i += 2; + if (nullsFound == 3) + break; + } + if (nullsFound != 3) + throw new PngjException("Bad formed PngChunkITXT chunk"); + key = ChunkHelper.toString(c.data, 0, nullsIdx[0]); + int i = nullsIdx[0] + 1; + compressed = c.data[i] == 0 ? false : true; + i++; + if (compressed && c.data[i] != 0) + throw new PngjException("Bad formed PngChunkITXT chunk - bad compression method "); + langTag = ChunkHelper.toString(c.data, i, nullsIdx[1] - i); + translatedTag = ChunkHelper.toStringUTF8(c.data, nullsIdx[1] + 1, nullsIdx[2] - nullsIdx[1] - 1); + i = nullsIdx[2] + 1; + if (compressed) { + final byte[] bytes = ChunkHelper.compressBytes(c.data, i, c.data.length - i, false); + val = ChunkHelper.toStringUTF8(bytes); + } else + val = ChunkHelper.toStringUTF8(c.data, i, c.data.length - i); + } - public boolean isCompressed() { - return compressed; - } + public boolean isCompressed() { + return compressed; + } - public void setCompressed(boolean compressed) { - this.compressed = compressed; - } + public void setCompressed(final boolean compressed) { + this.compressed = compressed; + } - public String getLangtag() { - return langTag; - } + public String getLangtag() { + return langTag; + } - public void setLangtag(String langtag) { - this.langTag = langtag; - } + public void setLangtag(final String langtag) { + langTag = langtag; + } - public String getTranslatedTag() { - return translatedTag; - } + public String getTranslatedTag() { + return translatedTag; + } - public void setTranslatedTag(String translatedTag) { - this.translatedTag = translatedTag; - } + public void setTranslatedTag(final String translatedTag) { + this.translatedTag = translatedTag; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkMultiple.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkMultiple.java index 8dd37524..0f822d24 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkMultiple.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkMultiple.java @@ -7,21 +7,22 @@ import ar.com.hjg.pngj.ImageInfo; */ public abstract class PngChunkMultiple extends PngChunk { - protected PngChunkMultiple(String id, ImageInfo imgInfo) { - super(id, imgInfo); - } + protected PngChunkMultiple(final String id, final ImageInfo imgInfo) { + super(id, imgInfo); + } - @Override - public final boolean allowsMultiple() { - return true; - } + @Override + public final boolean allowsMultiple() { + return true; + } - /** - * NOTE: this chunk uses the default Object's equals() hashCode() implementation. - * - * This is the right thing to do, normally. - * - * This is important, eg see ChunkList.removeFromList() - */ + /** + * NOTE: this chunk uses the default Object's equals() hashCode() + * implementation. + * + * This is the right thing to do, normally. + * + * This is important, eg see ChunkList.removeFromList() + */ } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkOFFS.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkOFFS.java index e47cf600..2f762a6c 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkOFFS.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkOFFS.java @@ -10,72 +10,72 @@ import ar.com.hjg.pngj.PngjException; * see http://www.libpng.org/pub/png/spec/register/pngext-1.3.0-pdg.html#C.oFFs */ public class PngChunkOFFS extends PngChunkSingle { - public final static String ID = "oFFs"; + public final static String ID = "oFFs"; - // http://www.libpng.org/pub/png/spec/register/pngext-1.3.0-pdg.html#C.oFFs - private long posX; - private long posY; - private int units; // 0: pixel 1:micrometer + // http://www.libpng.org/pub/png/spec/register/pngext-1.3.0-pdg.html#C.oFFs + private long posX; + private long posY; + private int units; // 0: pixel 1:micrometer - public PngChunkOFFS(ImageInfo info) { - super(ID, info); - } + public PngChunkOFFS(final ImageInfo info) { + super(PngChunkOFFS.ID, info); + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.BEFORE_IDAT; - } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.BEFORE_IDAT; + } - @Override - public ChunkRaw createRawChunk() { - ChunkRaw c = createEmptyChunk(9, true); - PngHelperInternal.writeInt4tobytes((int) posX, c.data, 0); - PngHelperInternal.writeInt4tobytes((int) posY, c.data, 4); - c.data[8] = (byte) units; - return c; - } + @Override + public ChunkRaw createRawChunk() { + final ChunkRaw c = createEmptyChunk(9, true); + PngHelperInternal.writeInt4tobytes((int) posX, c.data, 0); + PngHelperInternal.writeInt4tobytes((int) posY, c.data, 4); + c.data[8] = (byte) units; + return c; + } - @Override - public void parseFromRaw(ChunkRaw chunk) { - if (chunk.len != 9) - throw new PngjException("bad chunk length " + chunk); - posX = PngHelperInternal.readInt4fromBytes(chunk.data, 0); - if (posX < 0) - posX += 0x100000000L; - posY = PngHelperInternal.readInt4fromBytes(chunk.data, 4); - if (posY < 0) - posY += 0x100000000L; - units = PngHelperInternal.readInt1fromByte(chunk.data, 8); - } + @Override + public void parseFromRaw(final ChunkRaw chunk) { + if (chunk.len != 9) + throw new PngjException("bad chunk length " + chunk); + posX = PngHelperInternal.readInt4fromBytes(chunk.data, 0); + if (posX < 0) + posX += 0x100000000L; + posY = PngHelperInternal.readInt4fromBytes(chunk.data, 4); + if (posY < 0) + posY += 0x100000000L; + units = PngHelperInternal.readInt1fromByte(chunk.data, 8); + } - /** - * 0: pixel, 1:micrometer - */ - public int getUnits() { - return units; - } + /** + * 0: pixel, 1:micrometer + */ + public int getUnits() { + return units; + } - /** - * 0: pixel, 1:micrometer - */ - public void setUnits(int units) { - this.units = units; - } + /** + * 0: pixel, 1:micrometer + */ + public void setUnits(final int units) { + this.units = units; + } - public long getPosX() { - return posX; - } + public long getPosX() { + return posX; + } - public void setPosX(long posX) { - this.posX = posX; - } + public void setPosX(final long posX) { + this.posX = posX; + } - public long getPosY() { - return posY; - } + public long getPosY() { + return posY; + } - public void setPosY(long posY) { - this.posY = posY; - } + public void setPosY(final long posY) { + this.posY = posY; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkPHYS.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkPHYS.java index 98debb1f..acce8ed3 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkPHYS.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkPHYS.java @@ -10,98 +10,98 @@ import ar.com.hjg.pngj.PngjException; * see http://www.w3.org/TR/PNG/#11pHYs */ public class PngChunkPHYS extends PngChunkSingle { - public final static String ID = ChunkHelper.pHYs; + public final static String ID = ChunkHelper.pHYs; - // http://www.w3.org/TR/PNG/#11pHYs - private long pixelsxUnitX; - private long pixelsxUnitY; - private int units; // 0: unknown 1:metre + // http://www.w3.org/TR/PNG/#11pHYs + private long pixelsxUnitX; + private long pixelsxUnitY; + private int units; // 0: unknown 1:metre - public PngChunkPHYS(ImageInfo info) { - super(ID, info); - } + public PngChunkPHYS(final ImageInfo info) { + super(PngChunkPHYS.ID, info); + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.BEFORE_IDAT; - } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.BEFORE_IDAT; + } - @Override - public ChunkRaw createRawChunk() { - ChunkRaw c = createEmptyChunk(9, true); - PngHelperInternal.writeInt4tobytes((int) pixelsxUnitX, c.data, 0); - PngHelperInternal.writeInt4tobytes((int) pixelsxUnitY, c.data, 4); - c.data[8] = (byte) units; - return c; - } + @Override + public ChunkRaw createRawChunk() { + final ChunkRaw c = createEmptyChunk(9, true); + PngHelperInternal.writeInt4tobytes((int) pixelsxUnitX, c.data, 0); + PngHelperInternal.writeInt4tobytes((int) pixelsxUnitY, c.data, 4); + c.data[8] = (byte) units; + return c; + } - @Override - public void parseFromRaw(ChunkRaw chunk) { - if (chunk.len != 9) - throw new PngjException("bad chunk length " + chunk); - pixelsxUnitX = PngHelperInternal.readInt4fromBytes(chunk.data, 0); - if (pixelsxUnitX < 0) - pixelsxUnitX += 0x100000000L; - pixelsxUnitY = PngHelperInternal.readInt4fromBytes(chunk.data, 4); - if (pixelsxUnitY < 0) - pixelsxUnitY += 0x100000000L; - units = PngHelperInternal.readInt1fromByte(chunk.data, 8); - } + @Override + public void parseFromRaw(final ChunkRaw chunk) { + if (chunk.len != 9) + throw new PngjException("bad chunk length " + chunk); + pixelsxUnitX = PngHelperInternal.readInt4fromBytes(chunk.data, 0); + if (pixelsxUnitX < 0) + pixelsxUnitX += 0x100000000L; + pixelsxUnitY = PngHelperInternal.readInt4fromBytes(chunk.data, 4); + if (pixelsxUnitY < 0) + pixelsxUnitY += 0x100000000L; + units = PngHelperInternal.readInt1fromByte(chunk.data, 8); + } - public long getPixelsxUnitX() { - return pixelsxUnitX; - } + public long getPixelsxUnitX() { + return pixelsxUnitX; + } - public void setPixelsxUnitX(long pixelsxUnitX) { - this.pixelsxUnitX = pixelsxUnitX; - } + public void setPixelsxUnitX(final long pixelsxUnitX) { + this.pixelsxUnitX = pixelsxUnitX; + } - public long getPixelsxUnitY() { - return pixelsxUnitY; - } + public long getPixelsxUnitY() { + return pixelsxUnitY; + } - public void setPixelsxUnitY(long pixelsxUnitY) { - this.pixelsxUnitY = pixelsxUnitY; - } + public void setPixelsxUnitY(final long pixelsxUnitY) { + this.pixelsxUnitY = pixelsxUnitY; + } - public int getUnits() { - return units; - } + public int getUnits() { + return units; + } - public void setUnits(int units) { - this.units = units; - } + public void setUnits(final int units) { + this.units = units; + } - // special getters / setters + // special getters / setters - /** - * returns -1 if the physicial unit is unknown, or X-Y are not equal - */ - public double getAsDpi() { - if (units != 1 || pixelsxUnitX != pixelsxUnitY) - return -1; - return ((double) pixelsxUnitX) * 0.0254; - } + /** + * returns -1 if the physicial unit is unknown, or X-Y are not equal + */ + public double getAsDpi() { + if (units != 1 || pixelsxUnitX != pixelsxUnitY) + return -1; + return pixelsxUnitX * 0.0254; + } - /** - * returns -1 if the physicial unit is unknown - */ - public double[] getAsDpi2() { - if (units != 1) - return new double[] {-1, -1}; - return new double[] {((double) pixelsxUnitX) * 0.0254, ((double) pixelsxUnitY) * 0.0254}; - } + /** + * returns -1 if the physicial unit is unknown + */ + public double[] getAsDpi2() { + if (units != 1) + return new double[] { -1, -1 }; + return new double[] { pixelsxUnitX * 0.0254, pixelsxUnitY * 0.0254 }; + } - public void setAsDpi(double dpi) { - units = 1; - pixelsxUnitX = (long) (dpi / 0.0254 + 0.5); - pixelsxUnitY = pixelsxUnitX; - } + public void setAsDpi(final double dpi) { + units = 1; + pixelsxUnitX = (long) (dpi / 0.0254 + 0.5); + pixelsxUnitY = pixelsxUnitX; + } - public void setAsDpi2(double dpix, double dpiy) { - units = 1; - pixelsxUnitX = (long) (dpix / 0.0254 + 0.5); - pixelsxUnitY = (long) (dpiy / 0.0254 + 0.5); - } + public void setAsDpi2(final double dpix, final double dpiy) { + units = 1; + pixelsxUnitX = (long) (dpix / 0.0254 + 0.5); + pixelsxUnitY = (long) (dpiy / 0.0254 + 0.5); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkPLTE.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkPLTE.java index f647bde0..a0cfe734 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkPLTE.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkPLTE.java @@ -11,88 +11,85 @@ import ar.com.hjg.pngj.PngjException; * Critical chunk */ public class PngChunkPLTE extends PngChunkSingle { - public final static String ID = ChunkHelper.PLTE; + public final static String ID = ChunkHelper.PLTE; - // http://www.w3.org/TR/PNG/#11PLTE - private int nentries = 0; - /** - * RGB8 packed in one integer - */ - private int[] entries; + // http://www.w3.org/TR/PNG/#11PLTE + private int nentries = 0; + /** + * RGB8 packed in one integer + */ + private int[] entries; - public PngChunkPLTE(ImageInfo info) { - super(ID, info); - } + public PngChunkPLTE(final ImageInfo info) { + super(PngChunkPLTE.ID, info); + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.NA; - } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.NA; + } - @Override - public ChunkRaw createRawChunk() { - int len = 3 * nentries; - int[] rgb = new int[3]; - ChunkRaw c = createEmptyChunk(len, true); - for (int n = 0, i = 0; n < nentries; n++) { - getEntryRgb(n, rgb); - c.data[i++] = (byte) rgb[0]; - c.data[i++] = (byte) rgb[1]; - c.data[i++] = (byte) rgb[2]; - } - return c; - } + @Override + public ChunkRaw createRawChunk() { + final int len = 3 * nentries; + final int[] rgb = new int[3]; + final ChunkRaw c = createEmptyChunk(len, true); + for (int n = 0, i = 0; n < nentries; n++) { + getEntryRgb(n, rgb); + c.data[i++] = (byte) rgb[0]; + c.data[i++] = (byte) rgb[1]; + c.data[i++] = (byte) rgb[2]; + } + return c; + } - @Override - public void parseFromRaw(ChunkRaw chunk) { - setNentries(chunk.len / 3); - for (int n = 0, i = 0; n < nentries; n++) { - setEntry(n, (int) (chunk.data[i++] & 0xff), (int) (chunk.data[i++] & 0xff), - (int) (chunk.data[i++] & 0xff)); - } - } + @Override + public void parseFromRaw(final ChunkRaw chunk) { + setNentries(chunk.len / 3); + for (int n = 0, i = 0; n < nentries; n++) + setEntry(n, chunk.data[i++] & 0xff, chunk.data[i++] & 0xff, chunk.data[i++] & 0xff); + } - public void setNentries(int n) { - nentries = n; - if (nentries < 1 || nentries > 256) - throw new PngjException("invalid pallette - nentries=" + nentries); - if (entries == null || entries.length != nentries) { // alloc - entries = new int[nentries]; - } - } + public void setNentries(final int n) { + nentries = n; + if (nentries < 1 || nentries > 256) + throw new PngjException("invalid pallette - nentries=" + nentries); + if (entries == null || entries.length != nentries) + entries = new int[nentries]; + } - public int getNentries() { - return nentries; - } + public int getNentries() { + return nentries; + } - public void setEntry(int n, int r, int g, int b) { - entries[n] = ((r << 16) | (g << 8) | b); - } + public void setEntry(final int n, final int r, final int g, final int b) { + entries[n] = r << 16 | g << 8 | b; + } - public int getEntry(int n) { - return entries[n]; - } + public int getEntry(final int n) { + return entries[n]; + } - public void getEntryRgb(int n, int[] rgb) { - getEntryRgb(n, rgb, 0); - } + public void getEntryRgb(final int n, final int[] rgb) { + getEntryRgb(n, rgb, 0); + } - public void getEntryRgb(int n, int[] rgb, int offset) { - int v = entries[n]; - rgb[offset + 0] = ((v & 0xff0000) >> 16); - rgb[offset + 1] = ((v & 0xff00) >> 8); - rgb[offset + 2] = (v & 0xff); - } + public void getEntryRgb(final int n, final int[] rgb, final int offset) { + final int v = entries[n]; + rgb[offset + 0] = (v & 0xff0000) >> 16; + rgb[offset + 1] = (v & 0xff00) >> 8; + rgb[offset + 2] = v & 0xff; + } - public int minBitDepth() { - if (nentries <= 2) - return 1; - else if (nentries <= 4) - return 2; - else if (nentries <= 16) - return 4; - else - return 8; - } + public int minBitDepth() { + if (nentries <= 2) + return 1; + else if (nentries <= 4) + return 2; + else if (nentries <= 16) + return 4; + else + return 8; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkSBIT.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkSBIT.java index 6c6c7a62..f782b0ea 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkSBIT.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkSBIT.java @@ -12,103 +12,103 @@ import ar.com.hjg.pngj.PngjException; * this chunk structure depends on the image type */ public class PngChunkSBIT extends PngChunkSingle { - public final static String ID = ChunkHelper.sBIT; - // http://www.w3.org/TR/PNG/#11sBIT + public final static String ID = ChunkHelper.sBIT; + // http://www.w3.org/TR/PNG/#11sBIT - // significant bits - private int graysb, alphasb; - private int redsb, greensb, bluesb; + // significant bits + private int graysb, alphasb; + private int redsb, greensb, bluesb; - public PngChunkSBIT(ImageInfo info) { - super(ID, info); - } + public PngChunkSBIT(final ImageInfo info) { + super(PngChunkSBIT.ID, info); + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.BEFORE_PLTE_AND_IDAT; - } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.BEFORE_PLTE_AND_IDAT; + } - private int getCLen() { - int len = imgInfo.greyscale ? 1 : 3; - if (imgInfo.alpha) - len += 1; - return len; - } + private int getCLen() { + int len = imgInfo.greyscale ? 1 : 3; + if (imgInfo.alpha) + len += 1; + return len; + } - @Override - public void parseFromRaw(ChunkRaw c) { - if (c.len != getCLen()) - throw new PngjException("bad chunk length " + c); - if (imgInfo.greyscale) { - graysb = PngHelperInternal.readInt1fromByte(c.data, 0); - if (imgInfo.alpha) - alphasb = PngHelperInternal.readInt1fromByte(c.data, 1); - } else { - redsb = PngHelperInternal.readInt1fromByte(c.data, 0); - greensb = PngHelperInternal.readInt1fromByte(c.data, 1); - bluesb = PngHelperInternal.readInt1fromByte(c.data, 2); - if (imgInfo.alpha) - alphasb = PngHelperInternal.readInt1fromByte(c.data, 3); - } - } + @Override + public void parseFromRaw(final ChunkRaw c) { + if (c.len != getCLen()) + throw new PngjException("bad chunk length " + c); + if (imgInfo.greyscale) { + graysb = PngHelperInternal.readInt1fromByte(c.data, 0); + if (imgInfo.alpha) + alphasb = PngHelperInternal.readInt1fromByte(c.data, 1); + } else { + redsb = PngHelperInternal.readInt1fromByte(c.data, 0); + greensb = PngHelperInternal.readInt1fromByte(c.data, 1); + bluesb = PngHelperInternal.readInt1fromByte(c.data, 2); + if (imgInfo.alpha) + alphasb = PngHelperInternal.readInt1fromByte(c.data, 3); + } + } - @Override - public ChunkRaw createRawChunk() { - ChunkRaw c = null; - c = createEmptyChunk(getCLen(), true); - if (imgInfo.greyscale) { - c.data[0] = (byte) graysb; - if (imgInfo.alpha) - c.data[1] = (byte) alphasb; - } else { - c.data[0] = (byte) redsb; - c.data[1] = (byte) greensb; - c.data[2] = (byte) bluesb; - if (imgInfo.alpha) - c.data[3] = (byte) alphasb; - } - return c; - } + @Override + public ChunkRaw createRawChunk() { + ChunkRaw c = null; + c = createEmptyChunk(getCLen(), true); + if (imgInfo.greyscale) { + c.data[0] = (byte) graysb; + if (imgInfo.alpha) + c.data[1] = (byte) alphasb; + } else { + c.data[0] = (byte) redsb; + c.data[1] = (byte) greensb; + c.data[2] = (byte) bluesb; + if (imgInfo.alpha) + c.data[3] = (byte) alphasb; + } + return c; + } - public void setGraysb(int gray) { - if (!imgInfo.greyscale) - throw new PngjException("only greyscale images support this"); - graysb = gray; - } + public void setGraysb(final int gray) { + if (!imgInfo.greyscale) + throw new PngjException("only greyscale images support this"); + graysb = gray; + } - public int getGraysb() { - if (!imgInfo.greyscale) - throw new PngjException("only greyscale images support this"); - return graysb; - } + public int getGraysb() { + if (!imgInfo.greyscale) + throw new PngjException("only greyscale images support this"); + return graysb; + } - public void setAlphasb(int a) { - if (!imgInfo.alpha) - throw new PngjException("only images with alpha support this"); - alphasb = a; - } + public void setAlphasb(final int a) { + if (!imgInfo.alpha) + throw new PngjException("only images with alpha support this"); + alphasb = a; + } - public int getAlphasb() { - if (!imgInfo.alpha) - throw new PngjException("only images with alpha support this"); - return alphasb; - } + public int getAlphasb() { + if (!imgInfo.alpha) + throw new PngjException("only images with alpha support this"); + return alphasb; + } - /** - * Set rgb values - * - */ - public void setRGB(int r, int g, int b) { - if (imgInfo.greyscale || imgInfo.indexed) - throw new PngjException("only rgb or rgba images support this"); - redsb = r; - greensb = g; - bluesb = b; - } + /** + * Set rgb values + * + */ + public void setRGB(final int r, final int g, final int b) { + if (imgInfo.greyscale || imgInfo.indexed) + throw new PngjException("only rgb or rgba images support this"); + redsb = r; + greensb = g; + bluesb = b; + } - public int[] getRGB() { - if (imgInfo.greyscale || imgInfo.indexed) - throw new PngjException("only rgb or rgba images support this"); - return new int[] {redsb, greensb, bluesb}; - } + public int[] getRGB() { + if (imgInfo.greyscale || imgInfo.indexed) + throw new PngjException("only rgb or rgba images support this"); + return new int[] { redsb, greensb, bluesb }; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkSPLT.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkSPLT.java index 89bd57e6..423b41ff 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkSPLT.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkSPLT.java @@ -13,119 +13,117 @@ import ar.com.hjg.pngj.PngjException; * see http://www.w3.org/TR/PNG/#11sPLT */ public class PngChunkSPLT extends PngChunkMultiple { - public final static String ID = ChunkHelper.sPLT; + public final static String ID = ChunkHelper.sPLT; - // http://www.w3.org/TR/PNG/#11sPLT + // http://www.w3.org/TR/PNG/#11sPLT - private String palName; - private int sampledepth; // 8/16 - private int[] palette; // 5 elements per entry + private String palName; + private int sampledepth; // 8/16 + private int[] palette; // 5 elements per entry - public PngChunkSPLT(ImageInfo info) { - super(ID, info); - } + public PngChunkSPLT(final ImageInfo info) { + super(PngChunkSPLT.ID, info); + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.BEFORE_IDAT; - } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.BEFORE_IDAT; + } - @Override - public ChunkRaw createRawChunk() { - try { - ByteArrayOutputStream ba = new ByteArrayOutputStream(); - ba.write(ChunkHelper.toBytes(palName)); - ba.write(0); // separator - ba.write((byte) sampledepth); - int nentries = getNentries(); - for (int n = 0; n < nentries; n++) { - for (int i = 0; i < 4; i++) { - if (sampledepth == 8) - PngHelperInternal.writeByte(ba, (byte) palette[n * 5 + i]); - else - PngHelperInternal.writeInt2(ba, palette[n * 5 + i]); - } - PngHelperInternal.writeInt2(ba, palette[n * 5 + 4]); - } - byte[] b = ba.toByteArray(); - ChunkRaw chunk = createEmptyChunk(b.length, false); - chunk.data = b; - return chunk; - } catch (IOException e) { - throw new PngjException(e); - } - } + @Override + public ChunkRaw createRawChunk() { + try { + final ByteArrayOutputStream ba = new ByteArrayOutputStream(); + ba.write(ChunkHelper.toBytes(palName)); + ba.write(0); // separator + ba.write((byte) sampledepth); + final int nentries = getNentries(); + for (int n = 0; n < nentries; n++) { + for (int i = 0; i < 4; i++) + if (sampledepth == 8) + PngHelperInternal.writeByte(ba, (byte) palette[n * 5 + i]); + else + PngHelperInternal.writeInt2(ba, palette[n * 5 + i]); + PngHelperInternal.writeInt2(ba, palette[n * 5 + 4]); + } + final byte[] b = ba.toByteArray(); + final ChunkRaw chunk = createEmptyChunk(b.length, false); + chunk.data = b; + return chunk; + } catch (final IOException e) { + throw new PngjException(e); + } + } - @Override - public void parseFromRaw(ChunkRaw c) { - int t = -1; - for (int i = 0; i < c.data.length; i++) { // look for first zero - if (c.data[i] == 0) { - t = i; - break; - } - } - if (t <= 0 || t > c.data.length - 2) - throw new PngjException("bad sPLT chunk: no separator found"); - palName = ChunkHelper.toString(c.data, 0, t); - sampledepth = PngHelperInternal.readInt1fromByte(c.data, t + 1); - t += 2; - int nentries = (c.data.length - t) / (sampledepth == 8 ? 6 : 10); - palette = new int[nentries * 5]; - int r, g, b, a, f, ne; - ne = 0; - for (int i = 0; i < nentries; i++) { - if (sampledepth == 8) { - r = PngHelperInternal.readInt1fromByte(c.data, t++); - g = PngHelperInternal.readInt1fromByte(c.data, t++); - b = PngHelperInternal.readInt1fromByte(c.data, t++); - a = PngHelperInternal.readInt1fromByte(c.data, t++); - } else { - r = PngHelperInternal.readInt2fromBytes(c.data, t); - t += 2; - g = PngHelperInternal.readInt2fromBytes(c.data, t); - t += 2; - b = PngHelperInternal.readInt2fromBytes(c.data, t); - t += 2; - a = PngHelperInternal.readInt2fromBytes(c.data, t); - t += 2; - } - f = PngHelperInternal.readInt2fromBytes(c.data, t); - t += 2; - palette[ne++] = r; - palette[ne++] = g; - palette[ne++] = b; - palette[ne++] = a; - palette[ne++] = f; - } - } + @Override + public void parseFromRaw(final ChunkRaw c) { + int t = -1; + for (int i = 0; i < c.data.length; i++) + if (c.data[i] == 0) { + t = i; + break; + } + if (t <= 0 || t > c.data.length - 2) + throw new PngjException("bad sPLT chunk: no separator found"); + palName = ChunkHelper.toString(c.data, 0, t); + sampledepth = PngHelperInternal.readInt1fromByte(c.data, t + 1); + t += 2; + final int nentries = (c.data.length - t) / (sampledepth == 8 ? 6 : 10); + palette = new int[nentries * 5]; + int r, g, b, a, f, ne; + ne = 0; + for (int i = 0; i < nentries; i++) { + if (sampledepth == 8) { + r = PngHelperInternal.readInt1fromByte(c.data, t++); + g = PngHelperInternal.readInt1fromByte(c.data, t++); + b = PngHelperInternal.readInt1fromByte(c.data, t++); + a = PngHelperInternal.readInt1fromByte(c.data, t++); + } else { + r = PngHelperInternal.readInt2fromBytes(c.data, t); + t += 2; + g = PngHelperInternal.readInt2fromBytes(c.data, t); + t += 2; + b = PngHelperInternal.readInt2fromBytes(c.data, t); + t += 2; + a = PngHelperInternal.readInt2fromBytes(c.data, t); + t += 2; + } + f = PngHelperInternal.readInt2fromBytes(c.data, t); + t += 2; + palette[ne++] = r; + palette[ne++] = g; + palette[ne++] = b; + palette[ne++] = a; + palette[ne++] = f; + } + } - public int getNentries() { - return palette.length / 5; - } + public int getNentries() { + return palette.length / 5; + } - public String getPalName() { - return palName; - } + public String getPalName() { + return palName; + } - public void setPalName(String palName) { - this.palName = palName; - } + public void setPalName(final String palName) { + this.palName = palName; + } - public int getSampledepth() { - return sampledepth; - } + public int getSampledepth() { + return sampledepth; + } - public void setSampledepth(int sampledepth) { - this.sampledepth = sampledepth; - } + public void setSampledepth(final int sampledepth) { + this.sampledepth = sampledepth; + } - public int[] getPalette() { - return palette; - } + public int[] getPalette() { + return palette; + } - public void setPalette(int[] palette) { - this.palette = palette; - } + public void setPalette(final int[] palette) { + this.palette = palette; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkSRGB.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkSRGB.java index ff54b4c8..de261e79 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkSRGB.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkSRGB.java @@ -10,46 +10,46 @@ import ar.com.hjg.pngj.PngjException; * see http://www.w3.org/TR/PNG/#11sRGB */ public class PngChunkSRGB extends PngChunkSingle { - public final static String ID = ChunkHelper.sRGB; + public final static String ID = ChunkHelper.sRGB; - // http://www.w3.org/TR/PNG/#11sRGB + // http://www.w3.org/TR/PNG/#11sRGB - public static final int RENDER_INTENT_Perceptual = 0; - public static final int RENDER_INTENT_Relative_colorimetric = 1; - public static final int RENDER_INTENT_Saturation = 2; - public static final int RENDER_INTENT_Absolute_colorimetric = 3; + public static final int RENDER_INTENT_Perceptual = 0; + public static final int RENDER_INTENT_Relative_colorimetric = 1; + public static final int RENDER_INTENT_Saturation = 2; + public static final int RENDER_INTENT_Absolute_colorimetric = 3; - private int intent; + private int intent; - public PngChunkSRGB(ImageInfo info) { - super(ID, info); - } + public PngChunkSRGB(final ImageInfo info) { + super(PngChunkSRGB.ID, info); + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.BEFORE_PLTE_AND_IDAT; - } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.BEFORE_PLTE_AND_IDAT; + } - @Override - public void parseFromRaw(ChunkRaw c) { - if (c.len != 1) - throw new PngjException("bad chunk length " + c); - intent = PngHelperInternal.readInt1fromByte(c.data, 0); - } + @Override + public void parseFromRaw(final ChunkRaw c) { + if (c.len != 1) + throw new PngjException("bad chunk length " + c); + intent = PngHelperInternal.readInt1fromByte(c.data, 0); + } - @Override - public ChunkRaw createRawChunk() { - ChunkRaw c = null; - c = createEmptyChunk(1, true); - c.data[0] = (byte) intent; - return c; - } + @Override + public ChunkRaw createRawChunk() { + ChunkRaw c = null; + c = createEmptyChunk(1, true); + c.data[0] = (byte) intent; + return c; + } - public int getIntent() { - return intent; - } + public int getIntent() { + return intent; + } - public void setIntent(int intent) { - this.intent = intent; - } + public void setIntent(final int intent) { + this.intent = intent; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkSTER.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkSTER.java index dd33c4d3..fe135767 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkSTER.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkSTER.java @@ -9,46 +9,46 @@ import ar.com.hjg.pngj.PngjException; * see http://www.libpng.org/pub/png/spec/register/pngext-1.3.0-pdg.html#C.sTER */ public class PngChunkSTER extends PngChunkSingle { - public final static String ID = "sTER"; + public final static String ID = "sTER"; - // http://www.libpng.org/pub/png/spec/register/pngext-1.3.0-pdg.html#C.sTER - private byte mode; // 0: cross-fuse layout 1: diverging-fuse layout + // http://www.libpng.org/pub/png/spec/register/pngext-1.3.0-pdg.html#C.sTER + private byte mode; // 0: cross-fuse layout 1: diverging-fuse layout - public PngChunkSTER(ImageInfo info) { - super(ID, info); - } + public PngChunkSTER(final ImageInfo info) { + super(PngChunkSTER.ID, info); + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.BEFORE_IDAT; - } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.BEFORE_IDAT; + } - @Override - public ChunkRaw createRawChunk() { - ChunkRaw c = createEmptyChunk(1, true); - c.data[0] = (byte) mode; - return c; - } + @Override + public ChunkRaw createRawChunk() { + final ChunkRaw c = createEmptyChunk(1, true); + c.data[0] = mode; + return c; + } - @Override - public void parseFromRaw(ChunkRaw chunk) { - if (chunk.len != 1) - throw new PngjException("bad chunk length " + chunk); - mode = chunk.data[0]; - } + @Override + public void parseFromRaw(final ChunkRaw chunk) { + if (chunk.len != 1) + throw new PngjException("bad chunk length " + chunk); + mode = chunk.data[0]; + } - /** - * 0: cross-fuse layout 1: diverging-fuse layout - */ - public byte getMode() { - return mode; - } + /** + * 0: cross-fuse layout 1: diverging-fuse layout + */ + public byte getMode() { + return mode; + } - /** - * 0: cross-fuse layout 1: diverging-fuse layout - */ - public void setMode(byte mode) { - this.mode = mode; - } + /** + * 0: cross-fuse layout 1: diverging-fuse layout + */ + public void setMode(final byte mode) { + this.mode = mode; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkSingle.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkSingle.java index 58c23494..a98df4e8 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkSingle.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkSingle.java @@ -3,41 +3,43 @@ package ar.com.hjg.pngj.chunks; import ar.com.hjg.pngj.ImageInfo; /** - * PNG chunk type (abstract) that does not allow multiple instances in same image. + * PNG chunk type (abstract) that does not allow multiple instances in same + * image. */ public abstract class PngChunkSingle extends PngChunk { - protected PngChunkSingle(String id, ImageInfo imgInfo) { - super(id, imgInfo); - } + protected PngChunkSingle(final String id, final ImageInfo imgInfo) { + super(id, imgInfo); + } - public final boolean allowsMultiple() { - return false; - } + @Override + public final boolean allowsMultiple() { + return false; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (id == null ? 0 : id.hashCode()); + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - PngChunkSingle other = (PngChunkSingle) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - return true; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final PngChunkSingle other = (PngChunkSingle) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + return true; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkTEXT.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkTEXT.java index ea404edc..efaa62d4 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkTEXT.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkTEXT.java @@ -9,36 +9,36 @@ import ar.com.hjg.pngj.PngjException; * see http://www.w3.org/TR/PNG/#11tEXt */ public class PngChunkTEXT extends PngChunkTextVar { - public final static String ID = ChunkHelper.tEXt; + public final static String ID = ChunkHelper.tEXt; - public PngChunkTEXT(ImageInfo info) { - super(ID, info); - } + public PngChunkTEXT(final ImageInfo info) { + super(PngChunkTEXT.ID, info); + } - public PngChunkTEXT(ImageInfo info, String key, String val) { - super(ID, info); - setKeyVal(key, val); - } + public PngChunkTEXT(final ImageInfo info, final String key, final String val) { + super(PngChunkTEXT.ID, info); + setKeyVal(key, val); + } - @Override - public ChunkRaw createRawChunk() { - if (key == null || key.trim().length() == 0) - throw new PngjException("Text chunk key must be non empty"); - byte[] b = ChunkHelper.toBytes(key + "\0" + val); - ChunkRaw chunk = createEmptyChunk(b.length, false); - chunk.data = b; - return chunk; - } + @Override + public ChunkRaw createRawChunk() { + if (key == null || key.trim().length() == 0) + throw new PngjException("Text chunk key must be non empty"); + final byte[] b = ChunkHelper.toBytes(key + "\0" + val); + final ChunkRaw chunk = createEmptyChunk(b.length, false); + chunk.data = b; + return chunk; + } - @Override - public void parseFromRaw(ChunkRaw c) { - int i; - for (i = 0; i < c.data.length; i++) - if (c.data[i] == 0) - break; - key = ChunkHelper.toString(c.data, 0, i); - i++; - val = i < c.data.length ? ChunkHelper.toString(c.data, i, c.data.length - i) : ""; - } + @Override + public void parseFromRaw(final ChunkRaw c) { + int i; + for (i = 0; i < c.data.length; i++) + if (c.data[i] == 0) + break; + key = ChunkHelper.toString(c.data, 0, i); + i++; + val = i < c.data.length ? ChunkHelper.toString(c.data, i, c.data.length - i) : ""; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkTIME.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkTIME.java index 21e15132..37fab915 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkTIME.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkTIME.java @@ -12,71 +12,72 @@ import ar.com.hjg.pngj.PngjException; * see http://www.w3.org/TR/PNG/#11tIME */ public class PngChunkTIME extends PngChunkSingle { - public final static String ID = ChunkHelper.tIME; + public final static String ID = ChunkHelper.tIME; - // http://www.w3.org/TR/PNG/#11tIME - private int year, mon, day, hour, min, sec; + // http://www.w3.org/TR/PNG/#11tIME + private int year, mon, day, hour, min, sec; - public PngChunkTIME(ImageInfo info) { - super(ID, info); - } + public PngChunkTIME(final ImageInfo info) { + super(PngChunkTIME.ID, info); + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.NONE; - } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.NONE; + } - @Override - public ChunkRaw createRawChunk() { - ChunkRaw c = createEmptyChunk(7, true); - PngHelperInternal.writeInt2tobytes(year, c.data, 0); - c.data[2] = (byte) mon; - c.data[3] = (byte) day; - c.data[4] = (byte) hour; - c.data[5] = (byte) min; - c.data[6] = (byte) sec; - return c; - } + @Override + public ChunkRaw createRawChunk() { + final ChunkRaw c = createEmptyChunk(7, true); + PngHelperInternal.writeInt2tobytes(year, c.data, 0); + c.data[2] = (byte) mon; + c.data[3] = (byte) day; + c.data[4] = (byte) hour; + c.data[5] = (byte) min; + c.data[6] = (byte) sec; + return c; + } - @Override - public void parseFromRaw(ChunkRaw chunk) { - if (chunk.len != 7) - throw new PngjException("bad chunk " + chunk); - year = PngHelperInternal.readInt2fromBytes(chunk.data, 0); - mon = PngHelperInternal.readInt1fromByte(chunk.data, 2); - day = PngHelperInternal.readInt1fromByte(chunk.data, 3); - hour = PngHelperInternal.readInt1fromByte(chunk.data, 4); - min = PngHelperInternal.readInt1fromByte(chunk.data, 5); - sec = PngHelperInternal.readInt1fromByte(chunk.data, 6); - } + @Override + public void parseFromRaw(final ChunkRaw chunk) { + if (chunk.len != 7) + throw new PngjException("bad chunk " + chunk); + year = PngHelperInternal.readInt2fromBytes(chunk.data, 0); + mon = PngHelperInternal.readInt1fromByte(chunk.data, 2); + day = PngHelperInternal.readInt1fromByte(chunk.data, 3); + hour = PngHelperInternal.readInt1fromByte(chunk.data, 4); + min = PngHelperInternal.readInt1fromByte(chunk.data, 5); + sec = PngHelperInternal.readInt1fromByte(chunk.data, 6); + } - public void setNow(int secsAgo) { - Calendar d = Calendar.getInstance(); - d.setTimeInMillis(System.currentTimeMillis() - 1000 * (long) secsAgo); - year = d.get(Calendar.YEAR); - mon = d.get(Calendar.MONTH) + 1; - day = d.get(Calendar.DAY_OF_MONTH); - hour = d.get(Calendar.HOUR_OF_DAY); - min = d.get(Calendar.MINUTE); - sec = d.get(Calendar.SECOND); - } + public void setNow(final int secsAgo) { + final Calendar d = Calendar.getInstance(); + d.setTimeInMillis(System.currentTimeMillis() - 1000 * (long) secsAgo); + year = d.get(Calendar.YEAR); + mon = d.get(Calendar.MONTH) + 1; + day = d.get(Calendar.DAY_OF_MONTH); + hour = d.get(Calendar.HOUR_OF_DAY); + min = d.get(Calendar.MINUTE); + sec = d.get(Calendar.SECOND); + } - public void setYMDHMS(int yearx, int monx, int dayx, int hourx, int minx, int secx) { - year = yearx; - mon = monx; - day = dayx; - hour = hourx; - min = minx; - sec = secx; - } + public void setYMDHMS(final int yearx, final int monx, final int dayx, final int hourx, final int minx, + final int secx) { + year = yearx; + mon = monx; + day = dayx; + hour = hourx; + min = minx; + sec = secx; + } - public int[] getYMDHMS() { - return new int[] {year, mon, day, hour, min, sec}; - } + public int[] getYMDHMS() { + return new int[] { year, mon, day, hour, min, sec }; + } - /** format YYYY/MM/DD HH:mm:SS */ - public String getAsString() { - return String.format("%04d/%02d/%02d %02d:%02d:%02d", year, mon, day, hour, min, sec); - } + /** format YYYY/MM/DD HH:mm:SS */ + public String getAsString() { + return String.format("%04d/%02d/%02d %02d:%02d:%02d", year, mon, day, hour, min, sec); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkTRNS.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkTRNS.java index 82ad30fd..dd507304 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkTRNS.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkTRNS.java @@ -12,138 +12,139 @@ import ar.com.hjg.pngj.PngjException; * this chunk structure depends on the image type */ public class PngChunkTRNS extends PngChunkSingle { - public final static String ID = ChunkHelper.tRNS; + public final static String ID = ChunkHelper.tRNS; - // http://www.w3.org/TR/PNG/#11tRNS + // http://www.w3.org/TR/PNG/#11tRNS - // only one of these is meaningful, depending on the image type - private int gray; - private int red, green, blue; - private int[] paletteAlpha = new int[] {}; + // only one of these is meaningful, depending on the image type + private int gray; + private int red, green, blue; + private int[] paletteAlpha = new int[] {}; - public PngChunkTRNS(ImageInfo info) { - super(ID, info); - } + public PngChunkTRNS(final ImageInfo info) { + super(PngChunkTRNS.ID, info); + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.AFTER_PLTE_BEFORE_IDAT; - } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.AFTER_PLTE_BEFORE_IDAT; + } - @Override - public ChunkRaw createRawChunk() { - ChunkRaw c = null; - if (imgInfo.greyscale) { - c = createEmptyChunk(2, true); - PngHelperInternal.writeInt2tobytes(gray, c.data, 0); - } else if (imgInfo.indexed) { - c = createEmptyChunk(paletteAlpha.length, true); - for (int n = 0; n < c.len; n++) { - c.data[n] = (byte) paletteAlpha[n]; - } - } else { - c = createEmptyChunk(6, true); - PngHelperInternal.writeInt2tobytes(red, c.data, 0); - PngHelperInternal.writeInt2tobytes(green, c.data, 0); - PngHelperInternal.writeInt2tobytes(blue, c.data, 0); - } - return c; - } + @Override + public ChunkRaw createRawChunk() { + ChunkRaw c = null; + if (imgInfo.greyscale) { + c = createEmptyChunk(2, true); + PngHelperInternal.writeInt2tobytes(gray, c.data, 0); + } else if (imgInfo.indexed) { + c = createEmptyChunk(paletteAlpha.length, true); + for (int n = 0; n < c.len; n++) + c.data[n] = (byte) paletteAlpha[n]; + } else { + c = createEmptyChunk(6, true); + PngHelperInternal.writeInt2tobytes(red, c.data, 0); + PngHelperInternal.writeInt2tobytes(green, c.data, 0); + PngHelperInternal.writeInt2tobytes(blue, c.data, 0); + } + return c; + } - @Override - public void parseFromRaw(ChunkRaw c) { - if (imgInfo.greyscale) { - gray = PngHelperInternal.readInt2fromBytes(c.data, 0); - } else if (imgInfo.indexed) { - int nentries = c.data.length; - paletteAlpha = new int[nentries]; - for (int n = 0; n < nentries; n++) { - paletteAlpha[n] = (int) (c.data[n] & 0xff); - } - } else { - red = PngHelperInternal.readInt2fromBytes(c.data, 0); - green = PngHelperInternal.readInt2fromBytes(c.data, 2); - blue = PngHelperInternal.readInt2fromBytes(c.data, 4); - } - } + @Override + public void parseFromRaw(final ChunkRaw c) { + if (imgInfo.greyscale) + gray = PngHelperInternal.readInt2fromBytes(c.data, 0); + else if (imgInfo.indexed) { + final int nentries = c.data.length; + paletteAlpha = new int[nentries]; + for (int n = 0; n < nentries; n++) + paletteAlpha[n] = c.data[n] & 0xff; + } else { + red = PngHelperInternal.readInt2fromBytes(c.data, 0); + green = PngHelperInternal.readInt2fromBytes(c.data, 2); + blue = PngHelperInternal.readInt2fromBytes(c.data, 4); + } + } - /** - * Set rgb values - * - */ - public void setRGB(int r, int g, int b) { - if (imgInfo.greyscale || imgInfo.indexed) - throw new PngjException("only rgb or rgba images support this"); - red = r; - green = g; - blue = b; - } + /** + * Set rgb values + * + */ + public void setRGB(final int r, final int g, final int b) { + if (imgInfo.greyscale || imgInfo.indexed) + throw new PngjException("only rgb or rgba images support this"); + red = r; + green = g; + blue = b; + } - public int[] getRGB() { - if (imgInfo.greyscale || imgInfo.indexed) - throw new PngjException("only rgb or rgba images support this"); - return new int[] {red, green, blue}; - } + public int[] getRGB() { + if (imgInfo.greyscale || imgInfo.indexed) + throw new PngjException("only rgb or rgba images support this"); + return new int[] { red, green, blue }; + } - public int getRGB888() { - if (imgInfo.greyscale || imgInfo.indexed) - throw new PngjException("only rgb or rgba images support this"); - return (red << 16) | (green << 8) | blue; - } + public int getRGB888() { + if (imgInfo.greyscale || imgInfo.indexed) + throw new PngjException("only rgb or rgba images support this"); + return red << 16 | green << 8 | blue; + } - public void setGray(int g) { - if (!imgInfo.greyscale) - throw new PngjException("only grayscale images support this"); - gray = g; - } + public void setGray(final int g) { + if (!imgInfo.greyscale) + throw new PngjException("only grayscale images support this"); + gray = g; + } - public int getGray() { - if (!imgInfo.greyscale) - throw new PngjException("only grayscale images support this"); - return gray; - } + public int getGray() { + if (!imgInfo.greyscale) + throw new PngjException("only grayscale images support this"); + return gray; + } - /** - * Sets the length of the palette alpha. This should be followed by #setNentriesPalAlpha - * - * @param idx index inside the table - * @param val alpha value (0-255) - */ - public void setEntryPalAlpha(int idx, int val) { - paletteAlpha[idx] = val; - } + /** + * Sets the length of the palette alpha. This should be followed by + * #setNentriesPalAlpha + * + * @param idx + * index inside the table + * @param val + * alpha value (0-255) + */ + public void setEntryPalAlpha(final int idx, final int val) { + paletteAlpha[idx] = val; + } - public void setNentriesPalAlpha(int len) { - paletteAlpha = new int[len]; - } + public void setNentriesPalAlpha(final int len) { + paletteAlpha = new int[len]; + } - /** - * WARNING: non deep copy. See also {@link #setNentriesPalAlpha(int)} {@link #setEntryPalAlpha(int, int)} - */ - public void setPalAlpha(int[] palAlpha) { - if (!imgInfo.indexed) - throw new PngjException("only indexed images support this"); - paletteAlpha = palAlpha; - } + /** + * WARNING: non deep copy. See also {@link #setNentriesPalAlpha(int)} + * {@link #setEntryPalAlpha(int, int)} + */ + public void setPalAlpha(final int[] palAlpha) { + if (!imgInfo.indexed) + throw new PngjException("only indexed images support this"); + paletteAlpha = palAlpha; + } - /** - * WARNING: non deep copy - */ - public int[] getPalletteAlpha() { - return paletteAlpha; - } - - /** - * to use when only one pallete index is set as totally transparent - */ - public void setIndexEntryAsTransparent(int palAlphaIndex) { - if (!imgInfo.indexed) - throw new PngjException("only indexed images support this"); - paletteAlpha = new int[] {palAlphaIndex + 1}; - for (int i = 0; i < palAlphaIndex; i++) - paletteAlpha[i] = 255; - paletteAlpha[palAlphaIndex] = 0; - } + /** + * WARNING: non deep copy + */ + public int[] getPalletteAlpha() { + return paletteAlpha; + } + /** + * to use when only one pallete index is set as totally transparent + */ + public void setIndexEntryAsTransparent(final int palAlphaIndex) { + if (!imgInfo.indexed) + throw new PngjException("only indexed images support this"); + paletteAlpha = new int[] { palAlphaIndex + 1 }; + for (int i = 0; i < palAlphaIndex; i++) + paletteAlpha[i] = 255; + paletteAlpha[palAlphaIndex] = 0; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkTextVar.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkTextVar.java index 24ece4de..1591011a 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkTextVar.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkTextVar.java @@ -6,55 +6,55 @@ import ar.com.hjg.pngj.ImageInfo; * Superclass (abstract) for three textual chunks (TEXT, ITXT, ZTXT) */ public abstract class PngChunkTextVar extends PngChunkMultiple { - protected String key; // key/val: only for tEXt. lazy computed - protected String val; + protected String key; // key/val: only for tEXt. lazy computed + protected String val; - // http://www.w3.org/TR/PNG/#11keywords - public final static String KEY_Title = "Title"; // Short (one line) title or caption for image - public final static String KEY_Author = "Author"; // Name of image's creator - public final static String KEY_Description = "Description"; // Description of image (possibly - // long) - public final static String KEY_Copyright = "Copyright"; // Copyright notice - public final static String KEY_Creation_Time = "Creation Time"; // Time of original image creation - public final static String KEY_Software = "Software"; // Software used to create the image - public final static String KEY_Disclaimer = "Disclaimer"; // Legal disclaimer - public final static String KEY_Warning = "Warning"; // Warning of nature of content - public final static String KEY_Source = "Source"; // Device used to create the image - public final static String KEY_Comment = "Comment"; // Miscellaneous comment + // http://www.w3.org/TR/PNG/#11keywords + public final static String KEY_Title = "Title"; // Short (one line) title or caption for image + public final static String KEY_Author = "Author"; // Name of image's creator + public final static String KEY_Description = "Description"; // Description of image (possibly + // long) + public final static String KEY_Copyright = "Copyright"; // Copyright notice + public final static String KEY_Creation_Time = "Creation Time"; // Time of original image creation + public final static String KEY_Software = "Software"; // Software used to create the image + public final static String KEY_Disclaimer = "Disclaimer"; // Legal disclaimer + public final static String KEY_Warning = "Warning"; // Warning of nature of content + public final static String KEY_Source = "Source"; // Device used to create the image + public final static String KEY_Comment = "Comment"; // Miscellaneous comment - protected PngChunkTextVar(String id, ImageInfo info) { - super(id, info); - } + protected PngChunkTextVar(final String id, final ImageInfo info) { + super(id, info); + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.NONE; - } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.NONE; + } - public static class PngTxtInfo { - public String title; - public String author; - public String description; - public String creation_time;// = (new Date()).toString(); - public String software; - public String disclaimer; - public String warning; - public String source; - public String comment; + public static class PngTxtInfo { + public String title; + public String author; + public String description; + public String creation_time;// = (new Date()).toString(); + public String software; + public String disclaimer; + public String warning; + public String source; + public String comment; - } + } - public String getKey() { - return key; - } + public String getKey() { + return key; + } - public String getVal() { - return val; - } + public String getVal() { + return val; + } - public void setKeyVal(String key, String val) { - this.key = key; - this.val = val; - } + public void setKeyVal(final String key, final String val) { + this.key = key; + this.val = val; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkUNKNOWN.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkUNKNOWN.java index a9778f76..dbc8ad08 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkUNKNOWN.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkUNKNOWN.java @@ -9,32 +9,32 @@ import ar.com.hjg.pngj.ImageInfo; */ public class PngChunkUNKNOWN extends PngChunkMultiple { // unkown, custom or not - public PngChunkUNKNOWN(String id, ImageInfo info) { - super(id, info); - } + public PngChunkUNKNOWN(final String id, final ImageInfo info) { + super(id, info); + } - @Override - public ChunkOrderingConstraint getOrderingConstraint() { - return ChunkOrderingConstraint.NONE; - } + @Override + public ChunkOrderingConstraint getOrderingConstraint() { + return ChunkOrderingConstraint.NONE; + } - @Override - public ChunkRaw createRawChunk() { - return raw; - } + @Override + public ChunkRaw createRawChunk() { + return raw; + } - @Override - public void parseFromRaw(ChunkRaw c) { + @Override + public void parseFromRaw(final ChunkRaw c) { - } + } - /* does not do deep copy! */ - public byte[] getData() { - return raw.data; - } + /* does not do deep copy! */ + public byte[] getData() { + return raw.data; + } - /* does not do deep copy! */ - public void setData(byte[] data) { - raw.data = data; - } + /* does not do deep copy! */ + public void setData(final byte[] data) { + raw.data = data; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkZTXT.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkZTXT.java index 6b172e62..7ad9e69b 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkZTXT.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngChunkZTXT.java @@ -12,51 +12,50 @@ import ar.com.hjg.pngj.PngjException; * see http://www.w3.org/TR/PNG/#11zTXt */ public class PngChunkZTXT extends PngChunkTextVar { - public final static String ID = ChunkHelper.zTXt; + public final static String ID = ChunkHelper.zTXt; - // http://www.w3.org/TR/PNG/#11zTXt - public PngChunkZTXT(ImageInfo info) { - super(ID, info); - } + // http://www.w3.org/TR/PNG/#11zTXt + public PngChunkZTXT(final ImageInfo info) { + super(PngChunkZTXT.ID, info); + } - @Override - public ChunkRaw createRawChunk() { - if (key == null || key.trim().length() == 0) - throw new PngjException("Text chunk key must be non empty"); - try { - ByteArrayOutputStream ba = new ByteArrayOutputStream(); - ba.write(ChunkHelper.toBytes(key)); - ba.write(0); // separator - ba.write(0); // compression method: 0 - byte[] textbytes = ChunkHelper.compressBytes(ChunkHelper.toBytes(val), true); - ba.write(textbytes); - byte[] b = ba.toByteArray(); - ChunkRaw chunk = createEmptyChunk(b.length, false); - chunk.data = b; - return chunk; - } catch (IOException e) { - throw new PngjException(e); - } - } + @Override + public ChunkRaw createRawChunk() { + if (key == null || key.trim().length() == 0) + throw new PngjException("Text chunk key must be non empty"); + try { + final ByteArrayOutputStream ba = new ByteArrayOutputStream(); + ba.write(ChunkHelper.toBytes(key)); + ba.write(0); // separator + ba.write(0); // compression method: 0 + final byte[] textbytes = ChunkHelper.compressBytes(ChunkHelper.toBytes(val), true); + ba.write(textbytes); + final byte[] b = ba.toByteArray(); + final ChunkRaw chunk = createEmptyChunk(b.length, false); + chunk.data = b; + return chunk; + } catch (final IOException e) { + throw new PngjException(e); + } + } - @Override - public void parseFromRaw(ChunkRaw c) { - int nullsep = -1; - for (int i = 0; i < c.data.length; i++) { // look for first zero - if (c.data[i] != 0) - continue; - nullsep = i; - break; - } - if (nullsep < 0 || nullsep > c.data.length - 2) - throw new PngjException("bad zTXt chunk: no separator found"); - key = ChunkHelper.toString(c.data, 0, nullsep); - int compmet = (int) c.data[nullsep + 1]; - if (compmet != 0) - throw new PngjException("bad zTXt chunk: unknown compression method"); - byte[] uncomp = - ChunkHelper.compressBytes(c.data, nullsep + 2, c.data.length - nullsep - 2, false); // uncompress - val = ChunkHelper.toString(uncomp); - } + @Override + public void parseFromRaw(final ChunkRaw c) { + int nullsep = -1; + for (int i = 0; i < c.data.length; i++) { // look for first zero + if (c.data[i] != 0) + continue; + nullsep = i; + break; + } + if (nullsep < 0 || nullsep > c.data.length - 2) + throw new PngjException("bad zTXt chunk: no separator found"); + key = ChunkHelper.toString(c.data, 0, nullsep); + final int compmet = c.data[nullsep + 1]; + if (compmet != 0) + throw new PngjException("bad zTXt chunk: unknown compression method"); + final byte[] uncomp = ChunkHelper.compressBytes(c.data, nullsep + 2, c.data.length - nullsep - 2, false); // uncompress + val = ChunkHelper.toString(uncomp); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngMetadata.java b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngMetadata.java index 64912c45..46c30c92 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngMetadata.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/chunks/PngMetadata.java @@ -6,225 +6,230 @@ import java.util.List; import ar.com.hjg.pngj.PngjException; /** - * We consider "image metadata" every info inside the image except for the most basic image info (IHDR chunk - ImageInfo + * We consider "image metadata" every info inside the image except for the most + * basic image info (IHDR chunk - ImageInfo * class) and the pixels values. *

* This includes the palette (if present) and all the ancillary chunks *

- * This class provides a wrapper over the collection of chunks of a image (read or to write) and provides some high + * This class provides a wrapper over the collection of chunks of a image (read + * or to write) and provides some high * level methods to access them */ public class PngMetadata { - private final ChunksList chunkList; - private final boolean readonly; + private final ChunksList chunkList; + private final boolean readonly; - public PngMetadata(ChunksList chunks) { - this.chunkList = chunks; - if (chunks instanceof ChunksListForWrite) { - this.readonly = false; - } else { - this.readonly = true; - } - } + public PngMetadata(final ChunksList chunks) { + chunkList = chunks; + if (chunks instanceof ChunksListForWrite) + readonly = false; + else + readonly = true; + } - /** - * Queues the chunk at the writer - *

- * lazyOverwrite: if true, checks if there is a queued "equivalent" chunk and if so, overwrites it. However if that - * not check for already written chunks. - */ - public void queueChunk(final PngChunk c, boolean lazyOverwrite) { - ChunksListForWrite cl = getChunkListW(); - if (readonly) - throw new PngjException("cannot set chunk : readonly metadata"); - if (lazyOverwrite) { - ChunkHelper.trimList(cl.getQueuedChunks(), new ChunkPredicate() { - public boolean match(PngChunk c2) { - return ChunkHelper.equivalent(c, c2); - } - }); - } - cl.queue(c); - } + /** + * Queues the chunk at the writer + *

+ * lazyOverwrite: if true, checks if there is a queued "equivalent" chunk + * and if so, overwrites it. However if that + * not check for already written chunks. + */ + public void queueChunk(final PngChunk c, final boolean lazyOverwrite) { + final ChunksListForWrite cl = getChunkListW(); + if (readonly) + throw new PngjException("cannot set chunk : readonly metadata"); + if (lazyOverwrite) + ChunkHelper.trimList(cl.getQueuedChunks(), c2 -> ChunkHelper.equivalent(c, c2)); + cl.queue(c); + } - public void queueChunk(final PngChunk c) { - queueChunk(c, true); - } + public void queueChunk(final PngChunk c) { + queueChunk(c, true); + } - private ChunksListForWrite getChunkListW() { - return (ChunksListForWrite) chunkList; - } + private ChunksListForWrite getChunkListW() { + return (ChunksListForWrite) chunkList; + } - // ///// high level utility methods follow //////////// + // ///// high level utility methods follow //////////// - // //////////// DPI + // //////////// DPI - /** - * returns -1 if not found or dimension unknown - */ - public double[] getDpi() { - PngChunk c = chunkList.getById1(ChunkHelper.pHYs, true); - if (c == null) - return new double[] {-1, -1}; - else - return ((PngChunkPHYS) c).getAsDpi2(); - } + /** + * returns -1 if not found or dimension unknown + */ + public double[] getDpi() { + final PngChunk c = chunkList.getById1(ChunkHelper.pHYs, true); + if (c == null) + return new double[] { -1, -1 }; + else + return ((PngChunkPHYS) c).getAsDpi2(); + } - public void setDpi(double x) { - setDpi(x, x); - } + public void setDpi(final double x) { + setDpi(x, x); + } - public void setDpi(double x, double y) { - PngChunkPHYS c = new PngChunkPHYS(chunkList.imageInfo); - c.setAsDpi2(x, y); - queueChunk(c); - } + public void setDpi(final double x, final double y) { + final PngChunkPHYS c = new PngChunkPHYS(chunkList.imageInfo); + c.setAsDpi2(x, y); + queueChunk(c); + } - // //////////// TIME + // //////////// TIME - /** - * Creates a time chunk with current time, less secsAgo seconds - *

- * - * @return Returns the created-queued chunk, just in case you want to examine or modify it - */ - public PngChunkTIME setTimeNow(int secsAgo) { - PngChunkTIME c = new PngChunkTIME(chunkList.imageInfo); - c.setNow(secsAgo); - queueChunk(c); - return c; - } + /** + * Creates a time chunk with current time, less secsAgo seconds + *

+ * + * @return Returns the created-queued chunk, just in case you want to + * examine or modify it + */ + public PngChunkTIME setTimeNow(final int secsAgo) { + final PngChunkTIME c = new PngChunkTIME(chunkList.imageInfo); + c.setNow(secsAgo); + queueChunk(c); + return c; + } - public PngChunkTIME setTimeNow() { - return setTimeNow(0); - } + public PngChunkTIME setTimeNow() { + return setTimeNow(0); + } - /** - * Creates a time chunk with diven date-time - *

- * - * @return Returns the created-queued chunk, just in case you want to examine or modify it - */ - public PngChunkTIME setTimeYMDHMS(int yearx, int monx, int dayx, int hourx, int minx, int secx) { - PngChunkTIME c = new PngChunkTIME(chunkList.imageInfo); - c.setYMDHMS(yearx, monx, dayx, hourx, minx, secx); - queueChunk(c, true); - return c; - } + /** + * Creates a time chunk with diven date-time + *

+ * + * @return Returns the created-queued chunk, just in case you want to + * examine or modify it + */ + public PngChunkTIME setTimeYMDHMS(final int yearx, final int monx, final int dayx, final int hourx, final int minx, + final int secx) { + final PngChunkTIME c = new PngChunkTIME(chunkList.imageInfo); + c.setYMDHMS(yearx, monx, dayx, hourx, minx, secx); + queueChunk(c, true); + return c; + } - /** - * null if not found - */ - public PngChunkTIME getTime() { - return (PngChunkTIME) chunkList.getById1(ChunkHelper.tIME); - } + /** + * null if not found + */ + public PngChunkTIME getTime() { + return (PngChunkTIME) chunkList.getById1(ChunkHelper.tIME); + } - public String getTimeAsString() { - PngChunkTIME c = getTime(); - return c == null ? "" : c.getAsString(); - } + public String getTimeAsString() { + final PngChunkTIME c = getTime(); + return c == null ? "" : c.getAsString(); + } - // //////////// TEXT + // //////////// TEXT - /** - * Creates a text chunk and queue it. - *

- * - * @param k : key (latin1) - * @param val (arbitrary, should be latin1 if useLatin1) - * @param useLatin1 - * @param compress - * @return Returns the created-queued chunks, just in case you want to examine, touch it - */ - public PngChunkTextVar setText(String k, String val, boolean useLatin1, boolean compress) { - if (compress && !useLatin1) - throw new PngjException("cannot compress non latin text"); - PngChunkTextVar c; - if (useLatin1) { - if (compress) { - c = new PngChunkZTXT(chunkList.imageInfo); - } else { - c = new PngChunkTEXT(chunkList.imageInfo); - } - } else { - c = new PngChunkITXT(chunkList.imageInfo); - ((PngChunkITXT) c).setLangtag(k); // we use the same orig tag (this is not quite right) - } - c.setKeyVal(k, val); - queueChunk(c, true); - return c; - } + /** + * Creates a text chunk and queue it. + *

+ * + * @param k + * : key (latin1) + * @param val + * (arbitrary, should be latin1 if useLatin1) + * @param useLatin1 + * @param compress + * @return Returns the created-queued chunks, just in case you want to + * examine, touch it + */ + public PngChunkTextVar setText(final String k, final String val, final boolean useLatin1, final boolean compress) { + if (compress && !useLatin1) + throw new PngjException("cannot compress non latin text"); + PngChunkTextVar c; + if (useLatin1) { + if (compress) + c = new PngChunkZTXT(chunkList.imageInfo); + else + c = new PngChunkTEXT(chunkList.imageInfo); + } else { + c = new PngChunkITXT(chunkList.imageInfo); + ((PngChunkITXT) c).setLangtag(k); // we use the same orig tag (this is not quite right) + } + c.setKeyVal(k, val); + queueChunk(c, true); + return c; + } - public PngChunkTextVar setText(String k, String val) { - return setText(k, val, false, false); - } + public PngChunkTextVar setText(final String k, final String val) { + return setText(k, val, false, false); + } - /** - * gets all text chunks with a given key - *

- * returns null if not found - *

- * Warning: this does not check the "lang" key of iTxt - */ - @SuppressWarnings("unchecked") - public List getTxtsForKey(String k) { - @SuppressWarnings("rawtypes") - List c = new ArrayList(); - c.addAll(chunkList.getById(ChunkHelper.tEXt, k)); - c.addAll(chunkList.getById(ChunkHelper.zTXt, k)); - c.addAll(chunkList.getById(ChunkHelper.iTXt, k)); - return c; - } + /** + * gets all text chunks with a given key + *

+ * returns null if not found + *

+ * Warning: this does not check the "lang" key of iTxt + */ + @SuppressWarnings("unchecked") + public List getTxtsForKey(final String k) { + @SuppressWarnings("rawtypes") + final List c = new ArrayList(); + c.addAll(chunkList.getById(ChunkHelper.tEXt, k)); + c.addAll(chunkList.getById(ChunkHelper.zTXt, k)); + c.addAll(chunkList.getById(ChunkHelper.iTXt, k)); + return c; + } - /** - * Returns empty if not found, concatenated (with newlines) if multiple! - and trimmed - *

- * Use getTxtsForKey() if you don't want this behaviour - */ - public String getTxtForKey(String k) { - List li = getTxtsForKey(k); - if (li.isEmpty()) - return ""; - StringBuilder t = new StringBuilder(); - for (PngChunkTextVar c : li) - t.append(c.getVal()).append("\n"); - return t.toString().trim(); - } + /** + * Returns empty if not found, concatenated (with newlines) if multiple! - + * and trimmed + *

+ * Use getTxtsForKey() if you don't want this behaviour + */ + public String getTxtForKey(final String k) { + final List li = getTxtsForKey(k); + if (li.isEmpty()) + return ""; + final StringBuilder t = new StringBuilder(); + for (final PngChunkTextVar c : li) + t.append(c.getVal()).append("\n"); + return t.toString().trim(); + } - /** - * Returns the palette chunk, if present - * - * @return null if not present - */ - public PngChunkPLTE getPLTE() { - return (PngChunkPLTE) chunkList.getById1(PngChunkPLTE.ID); - } + /** + * Returns the palette chunk, if present + * + * @return null if not present + */ + public PngChunkPLTE getPLTE() { + return (PngChunkPLTE) chunkList.getById1(PngChunkPLTE.ID); + } - /** - * Creates a new empty palette chunk, queues it for write and return it to the caller, who should fill its entries - */ - public PngChunkPLTE createPLTEChunk() { - PngChunkPLTE plte = new PngChunkPLTE(chunkList.imageInfo); - queueChunk(plte); - return plte; - } + /** + * Creates a new empty palette chunk, queues it for write and return it to + * the caller, who should fill its entries + */ + public PngChunkPLTE createPLTEChunk() { + final PngChunkPLTE plte = new PngChunkPLTE(chunkList.imageInfo); + queueChunk(plte); + return plte; + } - /** - * Returns the TRNS chunk, if present - * - * @return null if not present - */ - public PngChunkTRNS getTRNS() { - return (PngChunkTRNS) chunkList.getById1(PngChunkTRNS.ID); - } + /** + * Returns the TRNS chunk, if present + * + * @return null if not present + */ + public PngChunkTRNS getTRNS() { + return (PngChunkTRNS) chunkList.getById1(PngChunkTRNS.ID); + } - /** - * Creates a new empty TRNS chunk, queues it for write and return it to the caller, who should fill its entries - */ - public PngChunkTRNS createTRNSChunk() { - PngChunkTRNS trns = new PngChunkTRNS(chunkList.imageInfo); - queueChunk(trns); - return trns; - } + /** + * Creates a new empty TRNS chunk, queues it for write and return it to the + * caller, who should fill its entries + */ + public PngChunkTRNS createTRNSChunk() { + final PngChunkTRNS trns = new PngChunkTRNS(chunkList.imageInfo); + queueChunk(trns); + return trns; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/pixels/CompressorStream.java b/teavm/src/main/java/ar/com/hjg/pngj/pixels/CompressorStream.java index 6b4d86f3..7c7425af 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/pixels/CompressorStream.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/pixels/CompressorStream.java @@ -5,156 +5,164 @@ import java.io.OutputStream; import ar.com.hjg.pngj.IDatChunkWriter; /** - * This is an OutputStream that compresses (via Deflater or a deflater-like object), and optionally passes the + * This is an OutputStream that compresses (via Deflater or a deflater-like + * object), and optionally passes the * compressed stream to another output stream. - * + * * It allows to compute in/out/ratio stats. - * - * It works as a stream (similar to DeflaterOutputStream), but it's peculiar in that it expects that each writes has a - * fixed length (other lenghts are accepted, but it's less efficient) and that the total amount of bytes is known (so it - * can close itself, but it can also be closed on demand) In PNGJ use, the block is typically a row (including filter + * + * It works as a stream (similar to DeflaterOutputStream), but it's peculiar in + * that it expects that each writes has a + * fixed length (other lenghts are accepted, but it's less efficient) and that + * the total amount of bytes is known (so it + * can close itself, but it can also be closed on demand) In PNGJ use, the block + * is typically a row (including filter * byte). - * - * We use this to do the real compression (with Deflate) but also to compute tentative estimators - * + * + * We use this to do the real compression (with Deflate) but also to compute + * tentative estimators + * * If not closed, it can be recicled via reset() - * - * + * + * */ public abstract class CompressorStream extends OutputStream { - protected IDatChunkWriter idatChunkWriter; - public final int blockLen; - public final long totalbytes; + protected IDatChunkWriter idatChunkWriter; + public final int blockLen; + public final long totalbytes; - boolean closed = false; - protected boolean done = false; - protected long bytesIn = 0; - protected long bytesOut = 0; - protected int block = -1; + boolean closed = false; + protected boolean done = false; + protected long bytesIn = 0; + protected long bytesOut = 0; + protected int block = -1; - /** optionally stores the first byte of each block (row) */ - private byte[] firstBytes; - protected boolean storeFirstByte = false; + /** optionally stores the first byte of each block (row) */ + private byte[] firstBytes; + protected boolean storeFirstByte = false; - /** - * - * @param idatCw Can be null (if we are only interested in compute compression ratio) - * @param blockLen Estimated maximum block length. If unknown, use -1. - * @param totalbytes Expected total bytes to be fed. If unknown, use -1. - */ - public CompressorStream(IDatChunkWriter idatCw, int blockLen, long totalbytes) { - this.idatChunkWriter = idatCw; - if (blockLen < 0) - blockLen = 4096; - if (totalbytes < 0) - totalbytes = Long.MAX_VALUE; - if (blockLen < 1 || totalbytes < 1) - throw new RuntimeException(" maxBlockLen or totalLen invalid"); - this.blockLen = blockLen; - this.totalbytes = totalbytes; - } + /** + * + * @param idatCw + * Can be null (if we are only interested in compute compression + * ratio) + * @param blockLen + * Estimated maximum block length. If unknown, use -1. + * @param totalbytes + * Expected total bytes to be fed. If unknown, use -1. + */ + public CompressorStream(final IDatChunkWriter idatCw, int blockLen, long totalbytes) { + idatChunkWriter = idatCw; + if (blockLen < 0) + blockLen = 4096; + if (totalbytes < 0) + totalbytes = Long.MAX_VALUE; + if (blockLen < 1 || totalbytes < 1) + throw new RuntimeException(" maxBlockLen or totalLen invalid"); + this.blockLen = blockLen; + this.totalbytes = totalbytes; + } - /** Releases resources. Idempotent. */ - @Override - public void close() { - done(); - if(idatChunkWriter!=null) idatChunkWriter.close(); - closed = true; - } + /** Releases resources. Idempotent. */ + @Override + public void close() { + done(); + if (idatChunkWriter != null) + idatChunkWriter.close(); + closed = true; + } - /** - * Will be called automatically when the number of bytes reaches the total expected Can be also be called from - * outside. This should set the flag done=true - */ - public abstract void done(); + /** + * Will be called automatically when the number of bytes reaches the total + * expected Can be also be called from + * outside. This should set the flag done=true + */ + public abstract void done(); - @Override - public final void write(byte[] data) { - write(data, 0, data.length); - } + @Override + public final void write(final byte[] data) { + write(data, 0, data.length); + } - @Override - public final void write(byte[] data, int off, int len) { - block++; - if (len <= blockLen) { // normal case - mywrite(data, off, len); - if (storeFirstByte && block < firstBytes.length) { - firstBytes[block] = data[off]; // only makes sense in this case - } - } else { - while (len > 0) { - mywrite(data, off, blockLen); - off += blockLen; - len -= blockLen; - } - } - if (bytesIn >= totalbytes) - done(); + @Override + public final void write(final byte[] data, int off, int len) { + block++; + if (len <= blockLen) { // normal case + mywrite(data, off, len); + if (storeFirstByte && block < firstBytes.length) + firstBytes[block] = data[off]; // only makes sense in this case + } else + while (len > 0) { + mywrite(data, off, blockLen); + off += blockLen; + len -= blockLen; + } + if (bytesIn >= totalbytes) + done(); - } + } - /** - * same as write, but guarantedd to not exceed blockLen The implementation should update bytesOut and bytesInt but not - * check for totalBytes - */ - public abstract void mywrite(byte[] data, int off, int len); + /** + * same as write, but guarantedd to not exceed blockLen The implementation + * should update bytesOut and bytesInt but not + * check for totalBytes + */ + public abstract void mywrite(byte[] data, int off, int len); + /** + * compressed/raw. This should be called only when done + */ + public final double getCompressionRatio() { + return bytesOut == 0 ? 1.0 : bytesOut / (double) bytesIn; + } - /** - * compressed/raw. This should be called only when done - */ - public final double getCompressionRatio() { - return bytesOut == 0 ? 1.0 : bytesOut / (double) bytesIn; - } + /** + * raw (input) bytes. This should be called only when done + */ + public final long getBytesRaw() { + return bytesIn; + } - /** - * raw (input) bytes. This should be called only when done - */ - public final long getBytesRaw() { - return bytesIn; - } + /** + * compressed (out) bytes. This should be called only when done + */ + public final long getBytesCompressed() { + return bytesOut; + } - /** - * compressed (out) bytes. This should be called only when done - */ - public final long getBytesCompressed() { - return bytesOut; - } + public boolean isClosed() { + return closed; + } - public boolean isClosed() { - return closed; - } + public boolean isDone() { + return done; + } - public boolean isDone() { - return done; - } + public byte[] getFirstBytes() { + return firstBytes; + } - public byte[] getFirstBytes() { - return firstBytes; - } + public void setStoreFirstByte(final boolean storeFirstByte, final int nblocks) { + this.storeFirstByte = storeFirstByte; + if (this.storeFirstByte) { + if (firstBytes == null || firstBytes.length < nblocks) + firstBytes = new byte[nblocks]; + } else + firstBytes = null; + } - public void setStoreFirstByte(boolean storeFirstByte, int nblocks) { - this.storeFirstByte = storeFirstByte; - if (this.storeFirstByte) { - if (firstBytes == null || firstBytes.length < nblocks) - firstBytes = new byte[nblocks]; - } else - firstBytes = null; - } - - public void reset() { - done(); - bytesIn = 0; - bytesOut = 0; - block = -1; - done = false; - } - - @Override - public void write(int i) { // should not be used - write(new byte[] {(byte) i}); - } + public void reset() { + done(); + bytesIn = 0; + bytesOut = 0; + block = -1; + done = false; + } + @Override + public void write(final int i) { // should not be used + write(new byte[] { (byte) i }); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/pixels/CompressorStreamDeflater.java b/teavm/src/main/java/ar/com/hjg/pngj/pixels/CompressorStreamDeflater.java index 24bb7e43..291bf4d6 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/pixels/CompressorStreamDeflater.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/pixels/CompressorStreamDeflater.java @@ -7,98 +7,99 @@ import ar.com.hjg.pngj.PngjOutputException; /** * CompressorStream backed by a Deflater. - * - * Note that the Deflater is not disposed after done, you should either recycle this with reset() or dispose it with + * + * Note that the Deflater is not disposed after done, you should either recycle + * this with reset() or dispose it with * close() - * + * */ public class CompressorStreamDeflater extends CompressorStream { - protected Deflater deflater; - protected byte[] buf1; // temporary storage of compressed bytes: only used if idatWriter is null - protected boolean deflaterIsOwn = true; + protected Deflater deflater; + protected byte[] buf1; // temporary storage of compressed bytes: only used if idatWriter is null + protected boolean deflaterIsOwn = true; - /** if a deflater is passed, it must be already reset. It will not be released on close */ - public CompressorStreamDeflater(IDatChunkWriter idatCw, int maxBlockLen, long totalLen, - Deflater def) { - super(idatCw, maxBlockLen, totalLen); - this.deflater = def == null ? new Deflater() : def; - this.deflaterIsOwn = def == null; - } + /** + * if a deflater is passed, it must be already reset. It will not be + * released on close + */ + public CompressorStreamDeflater(final IDatChunkWriter idatCw, final int maxBlockLen, final long totalLen, final Deflater def) { + super(idatCw, maxBlockLen, totalLen); + deflater = def == null ? new Deflater() : def; + deflaterIsOwn = def == null; + } - public CompressorStreamDeflater(IDatChunkWriter idatCw, int maxBlockLen, long totalLen) { - this(idatCw, maxBlockLen, totalLen, null); - } + public CompressorStreamDeflater(final IDatChunkWriter idatCw, final int maxBlockLen, final long totalLen) { + this(idatCw, maxBlockLen, totalLen, null); + } - public CompressorStreamDeflater(IDatChunkWriter idatCw, int maxBlockLen, long totalLen, - int deflaterCompLevel, int deflaterStrategy) { - this(idatCw, maxBlockLen, totalLen, new Deflater(deflaterCompLevel)); - this.deflaterIsOwn = true; - deflater.setStrategy(deflaterStrategy); - } + public CompressorStreamDeflater(final IDatChunkWriter idatCw, final int maxBlockLen, final long totalLen, final int deflaterCompLevel, final int deflaterStrategy) { + this(idatCw, maxBlockLen, totalLen, new Deflater(deflaterCompLevel)); + deflaterIsOwn = true; + deflater.setStrategy(deflaterStrategy); + } - @Override - public void mywrite(byte[] data, int off, final int len) { - if (deflater.finished() || done || closed) - throw new PngjOutputException("write beyond end of stream"); - deflater.setInput(data, off, len); - bytesIn += len; - while (!deflater.needsInput()) - deflate(); - } + @Override + public void mywrite(final byte[] data, final int off, final int len) { + if (deflater.finished() || done || closed) + throw new PngjOutputException("write beyond end of stream"); + deflater.setInput(data, off, len); + bytesIn += len; + while (!deflater.needsInput()) + deflate(); + } - protected void deflate() { - byte[] buf; - int off, n; - if (idatChunkWriter != null) { - buf = idatChunkWriter.getBuf(); - off = idatChunkWriter.getOffset(); - n = idatChunkWriter.getAvailLen(); - } else { - if (buf1 == null) - buf1 = new byte[4096]; - buf = buf1; - off = 0; - n = buf1.length; - } - int len = deflater.deflate(buf, off, n); - if (len > 0) { - if (idatChunkWriter != null) - idatChunkWriter.incrementOffset(len); - bytesOut += len; - } - } + protected void deflate() { + byte[] buf; + int off, n; + if (idatChunkWriter != null) { + buf = idatChunkWriter.getBuf(); + off = idatChunkWriter.getOffset(); + n = idatChunkWriter.getAvailLen(); + } else { + if (buf1 == null) + buf1 = new byte[4096]; + buf = buf1; + off = 0; + n = buf1.length; + } + final int len = deflater.deflate(buf, off, n); + if (len > 0) { + if (idatChunkWriter != null) + idatChunkWriter.incrementOffset(len); + bytesOut += len; + } + } - /** automatically called when done */ - @Override - public void done() { - if (done) - return; - if (!deflater.finished()) { - deflater.finish(); - while (!deflater.finished()) - deflate(); - } - done = true; - if (idatChunkWriter != null) - idatChunkWriter.close(); - } + /** automatically called when done */ + @Override + public void done() { + if (done) + return; + if (!deflater.finished()) { + deflater.finish(); + while (!deflater.finished()) + deflate(); + } + done = true; + if (idatChunkWriter != null) + idatChunkWriter.close(); + } - public void close() { - done(); - try { - if (deflaterIsOwn) { - deflater.end(); - } - } catch (Exception e) { - } - super.close(); - } + @Override + public void close() { + done(); + try { + if (deflaterIsOwn) + deflater.end(); + } catch (final Exception e) {} + super.close(); + } - @Override - public void reset() { - deflater.reset(); - super.reset(); - } + @Override + public void reset() { + deflater.reset(); + super.reset(); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/pixels/CompressorStreamLz4.java b/teavm/src/main/java/ar/com/hjg/pngj/pixels/CompressorStreamLz4.java index 299d3668..318918f2 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/pixels/CompressorStreamLz4.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/pixels/CompressorStreamLz4.java @@ -6,89 +6,89 @@ import ar.com.hjg.pngj.IDatChunkWriter; import ar.com.hjg.pngj.PngjOutputException; /** - * This class uses a quick compressor to get a rough estimate of deflate compression ratio. - * + * This class uses a quick compressor to get a rough estimate of deflate + * compression ratio. + * * This just ignores the outputStream, and the deflater related parameters */ public class CompressorStreamLz4 extends CompressorStream { - private final DeflaterEstimatorLz4 lz4; + private final DeflaterEstimatorLz4 lz4; - private byte[] buf; // lazily allocated, only if needed - private final int buffer_size; - // bufpos=bytes in buffer yet not compressed (bytesIn include this) - private int inbuf = 0; + private byte[] buf; // lazily allocated, only if needed + private final int buffer_size; + // bufpos=bytes in buffer yet not compressed (bytesIn include this) + private int inbuf = 0; - private static final int MAX_BUFFER_SIZE = 16000; + private static final int MAX_BUFFER_SIZE = 16000; - public CompressorStreamLz4(IDatChunkWriter os, int maxBlockLen, long totalLen) { - super(os, maxBlockLen, totalLen); - lz4 = new DeflaterEstimatorLz4(); - buffer_size = (int) (totalLen > MAX_BUFFER_SIZE ? MAX_BUFFER_SIZE : totalLen); - } + public CompressorStreamLz4(final IDatChunkWriter os, final int maxBlockLen, final long totalLen) { + super(os, maxBlockLen, totalLen); + lz4 = new DeflaterEstimatorLz4(); + buffer_size = (int) (totalLen > CompressorStreamLz4.MAX_BUFFER_SIZE ? CompressorStreamLz4.MAX_BUFFER_SIZE : totalLen); + } - public CompressorStreamLz4(IDatChunkWriter os, int maxBlockLen, long totalLen, Deflater def) { - this(os, maxBlockLen, totalLen);// edlfater ignored - } + public CompressorStreamLz4(final IDatChunkWriter os, final int maxBlockLen, final long totalLen, final Deflater def) { + this(os, maxBlockLen, totalLen);// edlfater ignored + } - public CompressorStreamLz4(IDatChunkWriter os, int maxBlockLen, long totalLen, - int deflaterCompLevel, int deflaterStrategy) { - this(os, maxBlockLen, totalLen); // paramters ignored - } + public CompressorStreamLz4(final IDatChunkWriter os, final int maxBlockLen, final long totalLen, final int deflaterCompLevel, final int deflaterStrategy) { + this(os, maxBlockLen, totalLen); // paramters ignored + } - @Override - public void mywrite(byte[] b, int off, int len) { - if (len == 0) - return; - if (done || closed) - throw new PngjOutputException("write beyond end of stream"); - bytesIn += len; - while (len > 0) { - if (inbuf == 0 && (len >= MAX_BUFFER_SIZE || bytesIn == totalbytes)) { - // direct copy (buffer might be null or empty) - bytesOut += lz4.compressEstim(b, off, len); - len = 0; - } else { - if (buf == null) - buf = new byte[buffer_size]; - int len1 = inbuf + len <= buffer_size ? len : buffer_size - inbuf; // to copy - if (len1 > 0) - System.arraycopy(b, off, buf, inbuf, len1); - inbuf += len1; - len -= len1; - off += len1; - if (inbuf == buffer_size) - compressFromBuffer(); - } - } - } + @Override + public void mywrite(final byte[] b, int off, int len) { + if (len == 0) + return; + if (done || closed) + throw new PngjOutputException("write beyond end of stream"); + bytesIn += len; + while (len > 0) + if (inbuf == 0 && (len >= CompressorStreamLz4.MAX_BUFFER_SIZE || bytesIn == totalbytes)) { + // direct copy (buffer might be null or empty) + bytesOut += lz4.compressEstim(b, off, len); + len = 0; + } else { + if (buf == null) + buf = new byte[buffer_size]; + final int len1 = inbuf + len <= buffer_size ? len : buffer_size - inbuf; // to copy + if (len1 > 0) + System.arraycopy(b, off, buf, inbuf, len1); + inbuf += len1; + len -= len1; + off += len1; + if (inbuf == buffer_size) + compressFromBuffer(); + } + } - void compressFromBuffer() { - if (inbuf > 0) { - bytesOut += lz4.compressEstim(buf, 0, inbuf); - inbuf = 0; - } - } + void compressFromBuffer() { + if (inbuf > 0) { + bytesOut += lz4.compressEstim(buf, 0, inbuf); + inbuf = 0; + } + } - @Override - public void done() { - if (!done) { - compressFromBuffer(); - done = true; - } - } + @Override + public void done() { + if (!done) { + compressFromBuffer(); + done = true; + } + } - @Override - public void close() { - done(); - if (!closed) { - super.close(); - buf = null; - } - } + @Override + public void close() { + done(); + if (!closed) { + super.close(); + buf = null; + } + } - public void reset() { - super.reset(); - } + @Override + public void reset() { + super.reset(); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/pixels/DeflaterEstimatorHjg.java b/teavm/src/main/java/ar/com/hjg/pngj/pixels/DeflaterEstimatorHjg.java index cfd332e2..4f8fab67 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/pixels/DeflaterEstimatorHjg.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/pixels/DeflaterEstimatorHjg.java @@ -1,258 +1,248 @@ package ar.com.hjg.pngj.pixels; - final public class DeflaterEstimatorHjg { - /** - * This object is stateless, it's thread safe and can be reused - */ - public DeflaterEstimatorHjg() {} + /** + * This object is stateless, it's thread safe and can be reused + */ + public DeflaterEstimatorHjg() {} - /** - * Estimates the length of the compressed bytes, as compressed by Lz4 WARNING: if larger than LZ4_64K_LIMIT it cuts it - * in fragments - * - * WARNING: if some part of the input is discarded, this should return the proportional (so that - * returnValue/srcLen=compressionRatio) - * - * @param src - * @param srcOff - * @param srcLen - * @return length of the compressed bytes - */ - public int compressEstim(byte[] src, int srcOff, final int srcLen) { - if (srcLen < 10) - return srcLen; // too small - int stride = LZ4_64K_LIMIT - 1; - int segments = (srcLen + stride - 1) / stride; - stride = srcLen / segments; - if (stride >= LZ4_64K_LIMIT - 1 || stride * segments > srcLen || segments < 1 || stride < 1) - throw new RuntimeException("?? " + srcLen); - int bytesIn = 0; - int bytesOut = 0; - int len = srcLen; - while (len > 0) { - if (len > stride) - len = stride; - bytesOut += compress64k(src, srcOff, len); - srcOff += len; - bytesIn += len; - len = srcLen - bytesIn; - } - double ratio = bytesOut / (double) bytesIn; - return bytesIn == srcLen ? bytesOut : (int) (ratio * srcLen + 0.5); - } + /** + * Estimates the length of the compressed bytes, as compressed by Lz4 + * WARNING: if larger than LZ4_64K_LIMIT it cuts it + * in fragments + * + * WARNING: if some part of the input is discarded, this should return the + * proportional (so that + * returnValue/srcLen=compressionRatio) + * + * @param src + * @param srcOff + * @param srcLen + * @return length of the compressed bytes + */ + public int compressEstim(final byte[] src, int srcOff, final int srcLen) { + if (srcLen < 10) + return srcLen; // too small + int stride = DeflaterEstimatorHjg.LZ4_64K_LIMIT - 1; + final int segments = (srcLen + stride - 1) / stride; + stride = srcLen / segments; + if (stride >= DeflaterEstimatorHjg.LZ4_64K_LIMIT - 1 || stride * segments > srcLen || segments < 1 || stride < 1) + throw new RuntimeException("?? " + srcLen); + int bytesIn = 0; + int bytesOut = 0; + int len = srcLen; + while (len > 0) { + if (len > stride) + len = stride; + bytesOut += DeflaterEstimatorHjg.compress64k(src, srcOff, len); + srcOff += len; + bytesIn += len; + len = srcLen - bytesIn; + } + final double ratio = bytesOut / (double) bytesIn; + return bytesIn == srcLen ? bytesOut : (int) (ratio * srcLen + 0.5); + } - public int compressEstim(byte[] src) { - return compressEstim(src, 0, src.length); - } + public int compressEstim(final byte[] src) { + return compressEstim(src, 0, src.length); + } - static final int MEMORY_USAGE = 14; - static final int NOT_COMPRESSIBLE_DETECTION_LEVEL = 6; // see SKIP_STRENGTH + static final int MEMORY_USAGE = 14; + static final int NOT_COMPRESSIBLE_DETECTION_LEVEL = 6; // see SKIP_STRENGTH - static final int MIN_MATCH = 4; + static final int MIN_MATCH = 4; - static final int HASH_LOG = MEMORY_USAGE - 2; - static final int HASH_TABLE_SIZE = 1 << HASH_LOG; + static final int HASH_LOG = DeflaterEstimatorHjg.MEMORY_USAGE - 2; + static final int HASH_TABLE_SIZE = 1 << DeflaterEstimatorHjg.HASH_LOG; - static final int SKIP_STRENGTH = Math.max(NOT_COMPRESSIBLE_DETECTION_LEVEL, 2); // 6 findMatchAttempts = - // 2^SKIP_STRENGTH+3 - static final int COPY_LENGTH = 8; - static final int LAST_LITERALS = 5; - static final int MF_LIMIT = COPY_LENGTH + MIN_MATCH; - static final int MIN_LENGTH = MF_LIMIT + 1; + static final int SKIP_STRENGTH = Math.max(DeflaterEstimatorHjg.NOT_COMPRESSIBLE_DETECTION_LEVEL, 2); // 6 findMatchAttempts = + // 2^SKIP_STRENGTH+3 + static final int COPY_LENGTH = 8; + static final int LAST_LITERALS = 5; + static final int MF_LIMIT = DeflaterEstimatorHjg.COPY_LENGTH + DeflaterEstimatorHjg.MIN_MATCH; + static final int MIN_LENGTH = DeflaterEstimatorHjg.MF_LIMIT + 1; - static final int MAX_DISTANCE = 1 << 16; + static final int MAX_DISTANCE = 1 << 16; - static final int ML_BITS = 4; - static final int ML_MASK = (1 << ML_BITS) - 1; - static final int RUN_BITS = 8 - ML_BITS; - static final int RUN_MASK = (1 << RUN_BITS) - 1; + static final int ML_BITS = 4; + static final int ML_MASK = (1 << DeflaterEstimatorHjg.ML_BITS) - 1; + static final int RUN_BITS = 8 - DeflaterEstimatorHjg.ML_BITS; + static final int RUN_MASK = (1 << DeflaterEstimatorHjg.RUN_BITS) - 1; - static final int LZ4_64K_LIMIT = (1 << 16) + (MF_LIMIT - 1); - static final int HASH_LOG_64K = HASH_LOG + 1; - static final int HASH_TABLE_SIZE_64K = 1 << HASH_LOG_64K; + static final int LZ4_64K_LIMIT = (1 << 16) + DeflaterEstimatorHjg.MF_LIMIT - 1; + static final int HASH_LOG_64K = DeflaterEstimatorHjg.HASH_LOG + 1; + static final int HASH_TABLE_SIZE_64K = 1 << DeflaterEstimatorHjg.HASH_LOG_64K; - static final int HASH_LOG_HC = 15; - static final int HASH_TABLE_SIZE_HC = 1 << HASH_LOG_HC; - static final int OPTIMAL_ML = ML_MASK - 1 + MIN_MATCH; + static final int HASH_LOG_HC = 15; + static final int HASH_TABLE_SIZE_HC = 1 << DeflaterEstimatorHjg.HASH_LOG_HC; + static final int OPTIMAL_ML = DeflaterEstimatorHjg.ML_MASK - 1 + DeflaterEstimatorHjg.MIN_MATCH; - static int compress64k(byte[] src, final int srcOff, final int srcLen) { - final int srcEnd = srcOff + srcLen; - final int srcLimit = srcEnd - LAST_LITERALS; - final int mflimit = srcEnd - MF_LIMIT; + static int compress64k(final byte[] src, final int srcOff, final int srcLen) { + final int srcEnd = srcOff + srcLen; + final int srcLimit = srcEnd - DeflaterEstimatorHjg.LAST_LITERALS; + final int mflimit = srcEnd - DeflaterEstimatorHjg.MF_LIMIT; - int sOff = srcOff, dOff = 0; + int sOff = srcOff, dOff = 0; - int anchor = sOff; + int anchor = sOff; - if (srcLen >= MIN_LENGTH) { + if (srcLen >= DeflaterEstimatorHjg.MIN_LENGTH) { - final short[] hashTable = new short[HASH_TABLE_SIZE_64K]; + final short[] hashTable = new short[DeflaterEstimatorHjg.HASH_TABLE_SIZE_64K]; - ++sOff; + ++sOff; - main: while (true) { + main: while (true) { - // find a match - int forwardOff = sOff; + // find a match + int forwardOff = sOff; - int ref; - int findMatchAttempts1 = (1 << SKIP_STRENGTH) + 3; // 64+3=67 - do { - sOff = forwardOff; - forwardOff += findMatchAttempts1++ >>> SKIP_STRENGTH; + int ref; + int findMatchAttempts1 = (1 << DeflaterEstimatorHjg.SKIP_STRENGTH) + 3; // 64+3=67 + do { + sOff = forwardOff; + forwardOff += findMatchAttempts1++ >>> DeflaterEstimatorHjg.SKIP_STRENGTH; - if (forwardOff > mflimit) { - break main; // ends all - } + if (forwardOff > mflimit) + break main; // ends all - final int h = hash64k(readInt(src, sOff)); - ref = srcOff + readShort(hashTable, h); - writeShort(hashTable, h, sOff - srcOff); - } while (!readIntEquals(src, ref, sOff)); + final int h = DeflaterEstimatorHjg.hash64k(DeflaterEstimatorHjg.readInt(src, sOff)); + ref = srcOff + DeflaterEstimatorHjg.readShort(hashTable, h); + DeflaterEstimatorHjg.writeShort(hashTable, h, sOff - srcOff); + } while (!DeflaterEstimatorHjg.readIntEquals(src, ref, sOff)); - // catch up - final int excess = commonBytesBackward(src, ref, sOff, srcOff, anchor); - sOff -= excess; - ref -= excess; - // sequence == refsequence - final int runLen = sOff - anchor; - dOff++; + // catch up + final int excess = DeflaterEstimatorHjg.commonBytesBackward(src, ref, sOff, srcOff, anchor); + sOff -= excess; + ref -= excess; + // sequence == refsequence + final int runLen = sOff - anchor; + dOff++; - if (runLen >= RUN_MASK) { - if (runLen > RUN_MASK) - dOff += (runLen - RUN_MASK) / 0xFF; - dOff++; - } - dOff += runLen; - while (true) { - // encode offset - dOff += 2; - // count nb matches - sOff += MIN_MATCH; - ref += MIN_MATCH; - final int matchLen = commonBytes(src, ref, sOff, srcLimit); - sOff += matchLen; - // encode match len - if (matchLen >= ML_MASK) { - if (matchLen >= ML_MASK + 0xFF) - dOff += (matchLen - ML_MASK) / 0xFF; - dOff++; - } - // test end of chunk - if (sOff > mflimit) { - anchor = sOff; - break main; - } - // fill table - writeShort(hashTable, hash64k(readInt(src, sOff - 2)), sOff - 2 - srcOff); - // test next position - final int h = hash64k(readInt(src, sOff)); - ref = srcOff + readShort(hashTable, h); - writeShort(hashTable, h, sOff - srcOff); - if (!readIntEquals(src, sOff, ref)) { - break; - } - dOff++; - } - // prepare next loop - anchor = sOff++; - } - } - int runLen = srcEnd - anchor; - if (runLen >= RUN_MASK + 0xFF) { - dOff += (runLen - RUN_MASK) / 0xFF; - } - dOff++; - dOff += runLen; - return dOff; - } + if (runLen >= DeflaterEstimatorHjg.RUN_MASK) { + if (runLen > DeflaterEstimatorHjg.RUN_MASK) + dOff += (runLen - DeflaterEstimatorHjg.RUN_MASK) / 0xFF; + dOff++; + } + dOff += runLen; + while (true) { + // encode offset + dOff += 2; + // count nb matches + sOff += DeflaterEstimatorHjg.MIN_MATCH; + ref += DeflaterEstimatorHjg.MIN_MATCH; + final int matchLen = DeflaterEstimatorHjg.commonBytes(src, ref, sOff, srcLimit); + sOff += matchLen; + // encode match len + if (matchLen >= DeflaterEstimatorHjg.ML_MASK) { + if (matchLen >= DeflaterEstimatorHjg.ML_MASK + 0xFF) + dOff += (matchLen - DeflaterEstimatorHjg.ML_MASK) / 0xFF; + dOff++; + } + // test end of chunk + if (sOff > mflimit) { + anchor = sOff; + break main; + } + // fill table + DeflaterEstimatorHjg.writeShort(hashTable, DeflaterEstimatorHjg.hash64k(DeflaterEstimatorHjg.readInt(src, sOff - 2)), sOff - 2 - srcOff); + // test next position + final int h = DeflaterEstimatorHjg.hash64k(DeflaterEstimatorHjg.readInt(src, sOff)); + ref = srcOff + DeflaterEstimatorHjg.readShort(hashTable, h); + DeflaterEstimatorHjg.writeShort(hashTable, h, sOff - srcOff); + if (!DeflaterEstimatorHjg.readIntEquals(src, sOff, ref)) + break; + dOff++; + } + // prepare next loop + anchor = sOff++; + } + } + final int runLen = srcEnd - anchor; + if (runLen >= DeflaterEstimatorHjg.RUN_MASK + 0xFF) + dOff += (runLen - DeflaterEstimatorHjg.RUN_MASK) / 0xFF; + dOff++; + dOff += runLen; + return dOff; + } - static final int maxCompressedLength(int length) { - if (length < 0) { - throw new IllegalArgumentException("length must be >= 0, got " + length); - } - return length + length / 255 + 16; - } + static int maxCompressedLength(final int length) { + if (length < 0) + throw new IllegalArgumentException("length must be >= 0, got " + length); + return length + length / 255 + 16; + } - static int hash(int i) { - return (i * -1640531535) >>> ((MIN_MATCH * 8) - HASH_LOG); - } + static int hash(final int i) { + return i * -1640531535 >>> DeflaterEstimatorHjg.MIN_MATCH * 8 - DeflaterEstimatorHjg.HASH_LOG; + } - static int hash64k(int i) { - return (i * -1640531535) >>> ((MIN_MATCH * 8) - HASH_LOG_64K); - } + static int hash64k(final int i) { + return i * -1640531535 >>> DeflaterEstimatorHjg.MIN_MATCH * 8 - DeflaterEstimatorHjg.HASH_LOG_64K; + } - static int readShortLittleEndian(byte[] buf, int i) { - return (buf[i] & 0xFF) | ((buf[i + 1] & 0xFF) << 8); - } + static int readShortLittleEndian(final byte[] buf, final int i) { + return buf[i] & 0xFF | (buf[i + 1] & 0xFF) << 8; + } - static boolean readIntEquals(byte[] buf, int i, int j) { - return buf[i] == buf[j] && buf[i + 1] == buf[j + 1] && buf[i + 2] == buf[j + 2] - && buf[i + 3] == buf[j + 3]; - } + static boolean readIntEquals(final byte[] buf, final int i, final int j) { + return buf[i] == buf[j] && buf[i + 1] == buf[j + 1] && buf[i + 2] == buf[j + 2] && buf[i + 3] == buf[j + 3]; + } - static int commonBytes(byte[] b, int o1, int o2, int limit) { - int count = 0; - while (o2 < limit && b[o1++] == b[o2++]) { - ++count; - } - return count; - } + static int commonBytes(final byte[] b, int o1, int o2, final int limit) { + int count = 0; + while (o2 < limit && b[o1++] == b[o2++]) + ++count; + return count; + } - static int commonBytesBackward(byte[] b, int o1, int o2, int l1, int l2) { - int count = 0; - while (o1 > l1 && o2 > l2 && b[--o1] == b[--o2]) { - ++count; - } - return count; - } + static int commonBytesBackward(final byte[] b, int o1, int o2, final int l1, final int l2) { + int count = 0; + while (o1 > l1 && o2 > l2 && b[--o1] == b[--o2]) + ++count; + return count; + } - static int readShort(short[] buf, int off) { - return buf[off] & 0xFFFF; - } + static int readShort(final short[] buf, final int off) { + return buf[off] & 0xFFFF; + } - static byte readByte(byte[] buf, int i) { - return buf[i]; - } + static byte readByte(final byte[] buf, final int i) { + return buf[i]; + } - static void checkRange(byte[] buf, int off) { - if (off < 0 || off >= buf.length) { - throw new ArrayIndexOutOfBoundsException(off); - } - } + static void checkRange(final byte[] buf, final int off) { + if (off < 0 || off >= buf.length) + throw new ArrayIndexOutOfBoundsException(off); + } - static void checkRange(byte[] buf, int off, int len) { - checkLength(len); - if (len > 0) { - checkRange(buf, off); - checkRange(buf, off + len - 1); - } - } + static void checkRange(final byte[] buf, final int off, final int len) { + DeflaterEstimatorHjg.checkLength(len); + if (len > 0) { + DeflaterEstimatorHjg.checkRange(buf, off); + DeflaterEstimatorHjg.checkRange(buf, off + len - 1); + } + } - static void checkLength(int len) { - if (len < 0) { - throw new IllegalArgumentException("lengths must be >= 0"); - } - } + static void checkLength(final int len) { + if (len < 0) + throw new IllegalArgumentException("lengths must be >= 0"); + } - static int readIntBE(byte[] buf, int i) { - return ((buf[i] & 0xFF) << 24) | ((buf[i + 1] & 0xFF) << 16) | ((buf[i + 2] & 0xFF) << 8) - | (buf[i + 3] & 0xFF); - } + static int readIntBE(final byte[] buf, final int i) { + return (buf[i] & 0xFF) << 24 | (buf[i + 1] & 0xFF) << 16 | (buf[i + 2] & 0xFF) << 8 | buf[i + 3] & 0xFF; + } - static int readIntLE(byte[] buf, int i) { - return (buf[i] & 0xFF) | ((buf[i + 1] & 0xFF) << 8) | ((buf[i + 2] & 0xFF) << 16) - | ((buf[i + 3] & 0xFF) << 24); - } + static int readIntLE(final byte[] buf, final int i) { + return buf[i] & 0xFF | (buf[i + 1] & 0xFF) << 8 | (buf[i + 2] & 0xFF) << 16 | (buf[i + 3] & 0xFF) << 24; + } - static int readInt(byte[] buf, int i) { - return readIntBE(buf, i); - } + static int readInt(final byte[] buf, final int i) { + return DeflaterEstimatorHjg.readIntBE(buf, i); + } - static void writeShort(short[] buf, int off, int v) { - buf[off] = (short) v; - } + static void writeShort(final short[] buf, final int off, final int v) { + buf[off] = (short) v; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/pixels/DeflaterEstimatorLz4.java b/teavm/src/main/java/ar/com/hjg/pngj/pixels/DeflaterEstimatorLz4.java index 9c69d9de..74d544c6 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/pixels/DeflaterEstimatorLz4.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/pixels/DeflaterEstimatorLz4.java @@ -3,270 +3,263 @@ package ar.com.hjg.pngj.pixels; import java.nio.ByteOrder; /** - * This estimator actually uses the LZ4 compression algorithm, and hopes that it's well correlated with Deflater. It's + * This estimator actually uses the LZ4 compression algorithm, and hopes that + * it's well correlated with Deflater. It's * about 3 to 4 times faster than Deflater. - * - * This is a modified heavily trimmed version of the net.jpountz.lz4.LZ4JavaSafeCompressor class plus some methods from - * other classes from LZ4 Java library: https://github.com/jpountz/lz4-java , originally licensed under the Apache + * + * This is a modified heavily trimmed version of the + * net.jpountz.lz4.LZ4JavaSafeCompressor class plus some methods from + * other classes from LZ4 Java library: https://github.com/jpountz/lz4-java , + * originally licensed under the Apache * License 2.0 */ final public class DeflaterEstimatorLz4 { - /** - * This object is stateless, it's thread safe and can be reused - */ - public DeflaterEstimatorLz4() {} + /** + * This object is stateless, it's thread safe and can be reused + */ + public DeflaterEstimatorLz4() {} - /** - * Estimates the length of the compressed bytes, as compressed by Lz4 WARNING: if larger than LZ4_64K_LIMIT it cuts it - * in fragments - * - * WARNING: if some part of the input is discarded, this should return the proportional (so that - * returnValue/srcLen=compressionRatio) - * - * @param src - * @param srcOff - * @param srcLen - * @return length of the compressed bytes - */ - public int compressEstim(byte[] src, int srcOff, final int srcLen) { - if (srcLen < 10) - return srcLen; // too small - int stride = LZ4_64K_LIMIT - 1; - int segments = (srcLen + stride - 1) / stride; - stride = srcLen / segments; - if (stride >= LZ4_64K_LIMIT - 1 || stride * segments > srcLen || segments < 1 || stride < 1) - throw new RuntimeException("?? " + srcLen); - int bytesIn = 0; - int bytesOut = 0; - int len = srcLen; - while (len > 0) { - if (len > stride) - len = stride; - bytesOut += compress64k(src, srcOff, len); - srcOff += len; - bytesIn += len; - len = srcLen - bytesIn; - } - double ratio = bytesOut / (double) bytesIn; - return bytesIn == srcLen ? bytesOut : (int) (ratio * srcLen + 0.5); - } + /** + * Estimates the length of the compressed bytes, as compressed by Lz4 + * WARNING: if larger than LZ4_64K_LIMIT it cuts it + * in fragments + * + * WARNING: if some part of the input is discarded, this should return the + * proportional (so that + * returnValue/srcLen=compressionRatio) + * + * @param src + * @param srcOff + * @param srcLen + * @return length of the compressed bytes + */ + public int compressEstim(final byte[] src, int srcOff, final int srcLen) { + if (srcLen < 10) + return srcLen; // too small + int stride = DeflaterEstimatorLz4.LZ4_64K_LIMIT - 1; + final int segments = (srcLen + stride - 1) / stride; + stride = srcLen / segments; + if (stride >= DeflaterEstimatorLz4.LZ4_64K_LIMIT - 1 || stride * segments > srcLen || segments < 1 || stride < 1) + throw new RuntimeException("?? " + srcLen); + int bytesIn = 0; + int bytesOut = 0; + int len = srcLen; + while (len > 0) { + if (len > stride) + len = stride; + bytesOut += DeflaterEstimatorLz4.compress64k(src, srcOff, len); + srcOff += len; + bytesIn += len; + len = srcLen - bytesIn; + } + final double ratio = bytesOut / (double) bytesIn; + return bytesIn == srcLen ? bytesOut : (int) (ratio * srcLen + 0.5); + } - public int compressEstim(byte[] src) { - return compressEstim(src, 0, src.length); - } + public int compressEstim(final byte[] src) { + return compressEstim(src, 0, src.length); + } - static final ByteOrder NATIVE_BYTE_ORDER = ByteOrder.nativeOrder(); + static final ByteOrder NATIVE_BYTE_ORDER = ByteOrder.nativeOrder(); - static final int MEMORY_USAGE = 14; - static final int NOT_COMPRESSIBLE_DETECTION_LEVEL = 6; + static final int MEMORY_USAGE = 14; + static final int NOT_COMPRESSIBLE_DETECTION_LEVEL = 6; - static final int MIN_MATCH = 4; + static final int MIN_MATCH = 4; - static final int HASH_LOG = MEMORY_USAGE - 2; - static final int HASH_TABLE_SIZE = 1 << HASH_LOG; + static final int HASH_LOG = DeflaterEstimatorLz4.MEMORY_USAGE - 2; + static final int HASH_TABLE_SIZE = 1 << DeflaterEstimatorLz4.HASH_LOG; - static final int SKIP_STRENGTH = Math.max(NOT_COMPRESSIBLE_DETECTION_LEVEL, 2); - static final int COPY_LENGTH = 8; - static final int LAST_LITERALS = 5; - static final int MF_LIMIT = COPY_LENGTH + MIN_MATCH; - static final int MIN_LENGTH = MF_LIMIT + 1; + static final int SKIP_STRENGTH = Math.max(DeflaterEstimatorLz4.NOT_COMPRESSIBLE_DETECTION_LEVEL, 2); + static final int COPY_LENGTH = 8; + static final int LAST_LITERALS = 5; + static final int MF_LIMIT = DeflaterEstimatorLz4.COPY_LENGTH + DeflaterEstimatorLz4.MIN_MATCH; + static final int MIN_LENGTH = DeflaterEstimatorLz4.MF_LIMIT + 1; - static final int MAX_DISTANCE = 1 << 16; + static final int MAX_DISTANCE = 1 << 16; - static final int ML_BITS = 4; - static final int ML_MASK = (1 << ML_BITS) - 1; - static final int RUN_BITS = 8 - ML_BITS; - static final int RUN_MASK = (1 << RUN_BITS) - 1; + static final int ML_BITS = 4; + static final int ML_MASK = (1 << DeflaterEstimatorLz4.ML_BITS) - 1; + static final int RUN_BITS = 8 - DeflaterEstimatorLz4.ML_BITS; + static final int RUN_MASK = (1 << DeflaterEstimatorLz4.RUN_BITS) - 1; - static final int LZ4_64K_LIMIT = (1 << 16) + (MF_LIMIT - 1); - static final int HASH_LOG_64K = HASH_LOG + 1; - static final int HASH_TABLE_SIZE_64K = 1 << HASH_LOG_64K; + static final int LZ4_64K_LIMIT = (1 << 16) + DeflaterEstimatorLz4.MF_LIMIT - 1; + static final int HASH_LOG_64K = DeflaterEstimatorLz4.HASH_LOG + 1; + static final int HASH_TABLE_SIZE_64K = 1 << DeflaterEstimatorLz4.HASH_LOG_64K; - static final int HASH_LOG_HC = 15; - static final int HASH_TABLE_SIZE_HC = 1 << HASH_LOG_HC; - static final int OPTIMAL_ML = ML_MASK - 1 + MIN_MATCH; + static final int HASH_LOG_HC = 15; + static final int HASH_TABLE_SIZE_HC = 1 << DeflaterEstimatorLz4.HASH_LOG_HC; + static final int OPTIMAL_ML = DeflaterEstimatorLz4.ML_MASK - 1 + DeflaterEstimatorLz4.MIN_MATCH; - static int compress64k(byte[] src, int srcOff, int srcLen) { - final int srcEnd = srcOff + srcLen; - final int srcLimit = srcEnd - LAST_LITERALS; - final int mflimit = srcEnd - MF_LIMIT; + static int compress64k(final byte[] src, final int srcOff, final int srcLen) { + final int srcEnd = srcOff + srcLen; + final int srcLimit = srcEnd - DeflaterEstimatorLz4.LAST_LITERALS; + final int mflimit = srcEnd - DeflaterEstimatorLz4.MF_LIMIT; - int sOff = srcOff, dOff = 0; + int sOff = srcOff, dOff = 0; - int anchor = sOff; + int anchor = sOff; - if (srcLen >= MIN_LENGTH) { + if (srcLen >= DeflaterEstimatorLz4.MIN_LENGTH) { - final short[] hashTable = new short[HASH_TABLE_SIZE_64K]; + final short[] hashTable = new short[DeflaterEstimatorLz4.HASH_TABLE_SIZE_64K]; - ++sOff; + ++sOff; - main: while (true) { + main: while (true) { - // find a match - int forwardOff = sOff; + // find a match + int forwardOff = sOff; - int ref; - int findMatchAttempts = (1 << SKIP_STRENGTH) + 3; - do { - sOff = forwardOff; - forwardOff += findMatchAttempts++ >>> SKIP_STRENGTH; + int ref; + int findMatchAttempts = (1 << DeflaterEstimatorLz4.SKIP_STRENGTH) + 3; + do { + sOff = forwardOff; + forwardOff += findMatchAttempts++ >>> DeflaterEstimatorLz4.SKIP_STRENGTH; - if (forwardOff > mflimit) { - break main; - } + if (forwardOff > mflimit) + break main; - final int h = hash64k(readInt(src, sOff)); - ref = srcOff + readShort(hashTable, h); - writeShort(hashTable, h, sOff - srcOff); - } while (!readIntEquals(src, ref, sOff)); + final int h = DeflaterEstimatorLz4.hash64k(DeflaterEstimatorLz4.readInt(src, sOff)); + ref = srcOff + DeflaterEstimatorLz4.readShort(hashTable, h); + DeflaterEstimatorLz4.writeShort(hashTable, h, sOff - srcOff); + } while (!DeflaterEstimatorLz4.readIntEquals(src, ref, sOff)); - // catch up - final int excess = commonBytesBackward(src, ref, sOff, srcOff, anchor); - sOff -= excess; - ref -= excess; - // sequence == refsequence - final int runLen = sOff - anchor; - dOff++; + // catch up + final int excess = DeflaterEstimatorLz4.commonBytesBackward(src, ref, sOff, srcOff, anchor); + sOff -= excess; + ref -= excess; + // sequence == refsequence + final int runLen = sOff - anchor; + dOff++; - if (runLen >= RUN_MASK) { - if (runLen > RUN_MASK) - dOff += (runLen - RUN_MASK) / 0xFF; - dOff++; - } - dOff += runLen; - while (true) { - // encode offset - dOff += 2; - // count nb matches - sOff += MIN_MATCH; - ref += MIN_MATCH; - final int matchLen = commonBytes(src, ref, sOff, srcLimit); - sOff += matchLen; - // encode match len - if (matchLen >= ML_MASK) { - if (matchLen >= ML_MASK + 0xFF) - dOff += (matchLen - ML_MASK) / 0xFF; - dOff++; - } - // test end of chunk - if (sOff > mflimit) { - anchor = sOff; - break main; - } - // fill table - writeShort(hashTable, hash64k(readInt(src, sOff - 2)), sOff - 2 - srcOff); - // test next position - final int h = hash64k(readInt(src, sOff)); - ref = srcOff + readShort(hashTable, h); - writeShort(hashTable, h, sOff - srcOff); - if (!readIntEquals(src, sOff, ref)) { - break; - } - dOff++; - } - // prepare next loop - anchor = sOff++; - } - } - int runLen = srcEnd - anchor; - if (runLen >= RUN_MASK + 0xFF) { - dOff += (runLen - RUN_MASK) / 0xFF; - } - dOff++; - dOff += runLen; - return dOff; - } + if (runLen >= DeflaterEstimatorLz4.RUN_MASK) { + if (runLen > DeflaterEstimatorLz4.RUN_MASK) + dOff += (runLen - DeflaterEstimatorLz4.RUN_MASK) / 0xFF; + dOff++; + } + dOff += runLen; + while (true) { + // encode offset + dOff += 2; + // count nb matches + sOff += DeflaterEstimatorLz4.MIN_MATCH; + ref += DeflaterEstimatorLz4.MIN_MATCH; + final int matchLen = DeflaterEstimatorLz4.commonBytes(src, ref, sOff, srcLimit); + sOff += matchLen; + // encode match len + if (matchLen >= DeflaterEstimatorLz4.ML_MASK) { + if (matchLen >= DeflaterEstimatorLz4.ML_MASK + 0xFF) + dOff += (matchLen - DeflaterEstimatorLz4.ML_MASK) / 0xFF; + dOff++; + } + // test end of chunk + if (sOff > mflimit) { + anchor = sOff; + break main; + } + // fill table + DeflaterEstimatorLz4.writeShort(hashTable, DeflaterEstimatorLz4.hash64k(DeflaterEstimatorLz4.readInt(src, sOff - 2)), sOff - 2 - srcOff); + // test next position + final int h = DeflaterEstimatorLz4.hash64k(DeflaterEstimatorLz4.readInt(src, sOff)); + ref = srcOff + DeflaterEstimatorLz4.readShort(hashTable, h); + DeflaterEstimatorLz4.writeShort(hashTable, h, sOff - srcOff); + if (!DeflaterEstimatorLz4.readIntEquals(src, sOff, ref)) + break; + dOff++; + } + // prepare next loop + anchor = sOff++; + } + } + final int runLen = srcEnd - anchor; + if (runLen >= DeflaterEstimatorLz4.RUN_MASK + 0xFF) + dOff += (runLen - DeflaterEstimatorLz4.RUN_MASK) / 0xFF; + dOff++; + dOff += runLen; + return dOff; + } - static final int maxCompressedLength(int length) { - if (length < 0) { - throw new IllegalArgumentException("length must be >= 0, got " + length); - } - return length + length / 255 + 16; - } + static int maxCompressedLength(final int length) { + if (length < 0) + throw new IllegalArgumentException("length must be >= 0, got " + length); + return length + length / 255 + 16; + } - static int hash(int i) { - return (i * -1640531535) >>> ((MIN_MATCH * 8) - HASH_LOG); - } + static int hash(final int i) { + return i * -1640531535 >>> DeflaterEstimatorLz4.MIN_MATCH * 8 - DeflaterEstimatorLz4.HASH_LOG; + } - static int hash64k(int i) { - return (i * -1640531535) >>> ((MIN_MATCH * 8) - HASH_LOG_64K); - } + static int hash64k(final int i) { + return i * -1640531535 >>> DeflaterEstimatorLz4.MIN_MATCH * 8 - DeflaterEstimatorLz4.HASH_LOG_64K; + } - static int readShortLittleEndian(byte[] buf, int i) { - return (buf[i] & 0xFF) | ((buf[i + 1] & 0xFF) << 8); - } + static int readShortLittleEndian(final byte[] buf, final int i) { + return buf[i] & 0xFF | (buf[i + 1] & 0xFF) << 8; + } - static boolean readIntEquals(byte[] buf, int i, int j) { - return buf[i] == buf[j] && buf[i + 1] == buf[j + 1] && buf[i + 2] == buf[j + 2] - && buf[i + 3] == buf[j + 3]; - } + static boolean readIntEquals(final byte[] buf, final int i, final int j) { + return buf[i] == buf[j] && buf[i + 1] == buf[j + 1] && buf[i + 2] == buf[j + 2] && buf[i + 3] == buf[j + 3]; + } - static int commonBytes(byte[] b, int o1, int o2, int limit) { - int count = 0; - while (o2 < limit && b[o1++] == b[o2++]) { - ++count; - } - return count; - } + static int commonBytes(final byte[] b, int o1, int o2, final int limit) { + int count = 0; + while (o2 < limit && b[o1++] == b[o2++]) + ++count; + return count; + } - static int commonBytesBackward(byte[] b, int o1, int o2, int l1, int l2) { - int count = 0; - while (o1 > l1 && o2 > l2 && b[--o1] == b[--o2]) { - ++count; - } - return count; - } + static int commonBytesBackward(final byte[] b, int o1, int o2, final int l1, final int l2) { + int count = 0; + while (o1 > l1 && o2 > l2 && b[--o1] == b[--o2]) + ++count; + return count; + } - static int readShort(short[] buf, int off) { - return buf[off] & 0xFFFF; - } + static int readShort(final short[] buf, final int off) { + return buf[off] & 0xFFFF; + } - static byte readByte(byte[] buf, int i) { - return buf[i]; - } + static byte readByte(final byte[] buf, final int i) { + return buf[i]; + } - static void checkRange(byte[] buf, int off) { - if (off < 0 || off >= buf.length) { - throw new ArrayIndexOutOfBoundsException(off); - } - } + static void checkRange(final byte[] buf, final int off) { + if (off < 0 || off >= buf.length) + throw new ArrayIndexOutOfBoundsException(off); + } - static void checkRange(byte[] buf, int off, int len) { - checkLength(len); - if (len > 0) { - checkRange(buf, off); - checkRange(buf, off + len - 1); - } - } + static void checkRange(final byte[] buf, final int off, final int len) { + DeflaterEstimatorLz4.checkLength(len); + if (len > 0) { + DeflaterEstimatorLz4.checkRange(buf, off); + DeflaterEstimatorLz4.checkRange(buf, off + len - 1); + } + } - static void checkLength(int len) { - if (len < 0) { - throw new IllegalArgumentException("lengths must be >= 0"); - } - } + static void checkLength(final int len) { + if (len < 0) + throw new IllegalArgumentException("lengths must be >= 0"); + } - static int readIntBE(byte[] buf, int i) { - return ((buf[i] & 0xFF) << 24) | ((buf[i + 1] & 0xFF) << 16) | ((buf[i + 2] & 0xFF) << 8) - | (buf[i + 3] & 0xFF); - } + static int readIntBE(final byte[] buf, final int i) { + return (buf[i] & 0xFF) << 24 | (buf[i + 1] & 0xFF) << 16 | (buf[i + 2] & 0xFF) << 8 | buf[i + 3] & 0xFF; + } - static int readIntLE(byte[] buf, int i) { - return (buf[i] & 0xFF) | ((buf[i + 1] & 0xFF) << 8) | ((buf[i + 2] & 0xFF) << 16) - | ((buf[i + 3] & 0xFF) << 24); - } + static int readIntLE(final byte[] buf, final int i) { + return buf[i] & 0xFF | (buf[i + 1] & 0xFF) << 8 | (buf[i + 2] & 0xFF) << 16 | (buf[i + 3] & 0xFF) << 24; + } - static int readInt(byte[] buf, int i) { - if (NATIVE_BYTE_ORDER == ByteOrder.BIG_ENDIAN) { - return readIntBE(buf, i); - } else { - return readIntLE(buf, i); - } - } + static int readInt(final byte[] buf, final int i) { + if (DeflaterEstimatorLz4.NATIVE_BYTE_ORDER == ByteOrder.BIG_ENDIAN) + return DeflaterEstimatorLz4.readIntBE(buf, i); + else + return DeflaterEstimatorLz4.readIntLE(buf, i); + } - static void writeShort(short[] buf, int off, int v) { - buf[off] = (short) v; - } + static void writeShort(final short[] buf, final int off, final int v) { + buf[off] = (short) v; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/pixels/FiltersPerformance.java b/teavm/src/main/java/ar/com/hjg/pngj/pixels/FiltersPerformance.java index 5a3c043c..bf35aa42 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/pixels/FiltersPerformance.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/pixels/FiltersPerformance.java @@ -10,194 +10,199 @@ import ar.com.hjg.pngj.PngjExceptionInternal; /** for use in adaptative strategy */ public class FiltersPerformance { - private final ImageInfo iminfo; - private double memoryA = 0.7; // empirical (not very critical: 0.72) - private int lastrow = -1; - private double[] absum = new double[5];// depending on the strategy not all values might be - // computed for all - private double[] entropy = new double[5]; - private double[] cost = new double[5]; - private int[] histog = new int[256]; // temporary, not normalized - private int lastprefered = -1; - private boolean initdone = false; - private double preferenceForNone = 1.0; // higher gives more preference to NONE + private final ImageInfo iminfo; + private double memoryA = 0.7; // empirical (not very critical: 0.72) + private int lastrow = -1; + private final double[] absum = new double[5];// depending on the strategy not all values might be + // computed for all + private final double[] entropy = new double[5]; + private final double[] cost = new double[5]; + private final int[] histog = new int[256]; // temporary, not normalized + private int lastprefered = -1; + private boolean initdone = false; + private double preferenceForNone = 1.0; // higher gives more preference to NONE - // this values are empirical (montecarlo), for RGB8 images with entropy estimator for NONE and - // memory=0.7 - // DONT MODIFY THIS - public static final double[] FILTER_WEIGHTS_DEFAULT = {0.73, 1.03, 0.97, 1.11, 1.22}; // lower is - // better! + // this values are empirical (montecarlo), for RGB8 images with entropy estimator for NONE and + // memory=0.7 + // DONT MODIFY THIS + public static final double[] FILTER_WEIGHTS_DEFAULT = { 0.73, 1.03, 0.97, 1.11, 1.22 }; // lower is + // better! - private double[] filter_weights = new double[] {-1, -1, -1, -1, -1}; + private final double[] filter_weights = new double[] { -1, -1, -1, -1, -1 }; - private final static double LOG2NI = -1.0 / Math.log(2.0); + private final static double LOG2NI = -1.0 / Math.log(2.0); - public FiltersPerformance(ImageInfo imgInfo) { - this.iminfo = imgInfo; - } + public FiltersPerformance(final ImageInfo imgInfo) { + iminfo = imgInfo; + } - private void init() { - if (filter_weights[0] < 0) {// has not been set from outside - System.arraycopy(FILTER_WEIGHTS_DEFAULT, 0, filter_weights, 0, 5); - double wNone = filter_weights[0]; - if (iminfo.bitDepth == 16) - wNone = 1.2; - else if (iminfo.alpha) - wNone = 0.8; - else if (iminfo.indexed || iminfo.bitDepth < 8) - wNone = 0.4; // we prefer NONE strongly - wNone /= preferenceForNone; - filter_weights[0] = wNone; - } - Arrays.fill(cost, 1.0); - initdone = true; - } + private void init() { + if (filter_weights[0] < 0) {// has not been set from outside + System.arraycopy(FiltersPerformance.FILTER_WEIGHTS_DEFAULT, 0, filter_weights, 0, 5); + double wNone = filter_weights[0]; + if (iminfo.bitDepth == 16) + wNone = 1.2; + else if (iminfo.alpha) + wNone = 0.8; + else if (iminfo.indexed || iminfo.bitDepth < 8) + wNone = 0.4; // we prefer NONE strongly + wNone /= preferenceForNone; + filter_weights[0] = wNone; + } + Arrays.fill(cost, 1.0); + initdone = true; + } - public void updateFromFiltered(FilterType ftype, byte[] rowff, int rown) { - updateFromRawOrFiltered(ftype, rowff, null, null, rown); - } + public void updateFromFiltered(final FilterType ftype, final byte[] rowff, final int rown) { + updateFromRawOrFiltered(ftype, rowff, null, null, rown); + } - /** alternative: computes statistic without filtering */ - public void updateFromRaw(FilterType ftype, byte[] rowb, byte[] rowbprev, int rown) { - updateFromRawOrFiltered(ftype, null, rowb, rowbprev, rown); - } + /** alternative: computes statistic without filtering */ + public void updateFromRaw(final FilterType ftype, final byte[] rowb, final byte[] rowbprev, final int rown) { + updateFromRawOrFiltered(ftype, null, rowb, rowbprev, rown); + } - private void updateFromRawOrFiltered(FilterType ftype, byte[] rowff, byte[] rowb, - byte[] rowbprev, int rown) { - if (!initdone) - init(); - if (rown != lastrow) { - Arrays.fill(absum, Double.NaN); - Arrays.fill(entropy, Double.NaN); - } - lastrow = rown; - if (rowff != null) - computeHistogram(rowff); - else - computeHistogramForFilter(ftype, rowb, rowbprev); - if (ftype == FilterType.FILTER_NONE) - entropy[ftype.val] = computeEntropyFromHistogram(); - else - absum[ftype.val] = computeAbsFromHistogram(); - } + private void updateFromRawOrFiltered(final FilterType ftype, final byte[] rowff, final byte[] rowb, + final byte[] rowbprev, final int rown) { + if (!initdone) + init(); + if (rown != lastrow) { + Arrays.fill(absum, Double.NaN); + Arrays.fill(entropy, Double.NaN); + } + lastrow = rown; + if (rowff != null) + computeHistogram(rowff); + else + computeHistogramForFilter(ftype, rowb, rowbprev); + if (ftype == FilterType.FILTER_NONE) + entropy[ftype.val] = computeEntropyFromHistogram(); + else + absum[ftype.val] = computeAbsFromHistogram(); + } - /* WARNING: this is not idempotent, call it just once per cycle (sigh) */ - public FilterType getPreferred() { - int fi = 0; - double vali = Double.MAX_VALUE, val = 0; // lower wins - for (int i = 0; i < 5; i++) { - if (!Double.isNaN(absum[i])) { - val = absum[i]; - } else if (!Double.isNaN(entropy[i])) { - val = (Math.pow(2.0, entropy[i]) - 1.0) * 0.5; - } else - continue; - val *= filter_weights[i]; - val = cost[i] * memoryA + (1 - memoryA) * val; - cost[i] = val; - if (val < vali) { - vali = val; - fi = i; - } - } - lastprefered = fi; - return FilterType.getByVal(lastprefered); - } + /* WARNING: this is not idempotent, call it just once per cycle (sigh) */ + public FilterType getPreferred() { + int fi = 0; + double vali = Double.MAX_VALUE, val = 0; // lower wins + for (int i = 0; i < 5; i++) { + if (!Double.isNaN(absum[i])) + val = absum[i]; + else if (!Double.isNaN(entropy[i])) + val = (Math.pow(2.0, entropy[i]) - 1.0) * 0.5; + else + continue; + val *= filter_weights[i]; + val = cost[i] * memoryA + (1 - memoryA) * val; + cost[i] = val; + if (val < vali) { + vali = val; + fi = i; + } + } + lastprefered = fi; + return FilterType.getByVal(lastprefered); + } - public final void computeHistogramForFilter(FilterType filterType, byte[] rowb, byte[] rowbprev) { - Arrays.fill(histog, 0); - int i, j, imax = iminfo.bytesPerRow; - switch (filterType) { - case FILTER_NONE: - for (i = 1; i <= imax; i++) - histog[rowb[i] & 0xFF]++; - break; - case FILTER_PAETH: - for (i = 1; i <= imax; i++) - histog[PngHelperInternal.filterRowPaeth(rowb[i], 0, rowbprev[i] & 0xFF, 0)]++; - for (j = 1, i = iminfo.bytesPixel + 1; i <= imax; i++, j++) - histog[PngHelperInternal.filterRowPaeth(rowb[i], rowb[j] & 0xFF, rowbprev[i] & 0xFF, - rowbprev[j] & 0xFF)]++; - break; - case FILTER_SUB: - for (i = 1; i <= iminfo.bytesPixel; i++) - histog[rowb[i] & 0xFF]++; - for (j = 1, i = iminfo.bytesPixel + 1; i <= imax; i++, j++) - histog[(rowb[i] - rowb[j]) & 0xFF]++; - break; - case FILTER_UP: - for (i = 1; i <= iminfo.bytesPerRow; i++) - histog[(rowb[i] - rowbprev[i]) & 0xFF]++; - break; - case FILTER_AVERAGE: - for (i = 1; i <= iminfo.bytesPixel; i++) - histog[((rowb[i] & 0xFF) - ((rowbprev[i] & 0xFF)) / 2) & 0xFF]++; - for (j = 1, i = iminfo.bytesPixel + 1; i <= imax; i++, j++) - histog[((rowb[i] & 0xFF) - ((rowbprev[i] & 0xFF) + (rowb[j] & 0xFF)) / 2) & 0xFF]++; - break; - default: - throw new PngjExceptionInternal("Bad filter:" + filterType); - } - } + public final void computeHistogramForFilter(final FilterType filterType, final byte[] rowb, final byte[] rowbprev) { + Arrays.fill(histog, 0); + int i, j; + final int imax = iminfo.bytesPerRow; + switch (filterType) { + case FILTER_NONE: + for (i = 1; i <= imax; i++) + histog[rowb[i] & 0xFF]++; + break; + case FILTER_PAETH: + for (i = 1; i <= imax; i++) + histog[PngHelperInternal.filterRowPaeth(rowb[i], 0, rowbprev[i] & 0xFF, 0)]++; + for (j = 1, i = iminfo.bytesPixel + 1; i <= imax; i++, j++) + histog[PngHelperInternal.filterRowPaeth(rowb[i], rowb[j] & 0xFF, rowbprev[i] & 0xFF, rowbprev[j] & 0xFF)]++; + break; + case FILTER_SUB: + for (i = 1; i <= iminfo.bytesPixel; i++) + histog[rowb[i] & 0xFF]++; + for (j = 1, i = iminfo.bytesPixel + 1; i <= imax; i++, j++) + histog[rowb[i] - rowb[j] & 0xFF]++; + break; + case FILTER_UP: + for (i = 1; i <= iminfo.bytesPerRow; i++) + histog[rowb[i] - rowbprev[i] & 0xFF]++; + break; + case FILTER_AVERAGE: + for (i = 1; i <= iminfo.bytesPixel; i++) + histog[(rowb[i] & 0xFF) - (rowbprev[i] & 0xFF) / 2 & 0xFF]++; + for (j = 1, i = iminfo.bytesPixel + 1; i <= imax; i++, j++) + histog[(rowb[i] & 0xFF) - ((rowbprev[i] & 0xFF) + (rowb[j] & 0xFF)) / 2 & 0xFF]++; + break; + default: + throw new PngjExceptionInternal("Bad filter:" + filterType); + } + } - public void computeHistogram(byte[] rowff) { - Arrays.fill(histog, 0); - for (int i = 1; i < iminfo.bytesPerRow; i++) - histog[rowff[i] & 0xFF]++; - } + public void computeHistogram(final byte[] rowff) { + Arrays.fill(histog, 0); + for (int i = 1; i < iminfo.bytesPerRow; i++) + histog[rowff[i] & 0xFF]++; + } - public double computeAbsFromHistogram() { - int s = 0; - for (int i = 1; i < 128; i++) - s += histog[i] * i; - for (int i = 128, j = 128; j > 0; i++, j--) - s += histog[i] * j; - return s / (double) iminfo.bytesPerRow; - } + public double computeAbsFromHistogram() { + int s = 0; + for (int i = 1; i < 128; i++) + s += histog[i] * i; + for (int i = 128, j = 128; j > 0; i++, j--) + s += histog[i] * j; + return s / (double) iminfo.bytesPerRow; + } - public final double computeEntropyFromHistogram() { - double s = 1.0 / iminfo.bytesPerRow; - double ls = Math.log(s); + public final double computeEntropyFromHistogram() { + final double s = 1.0 / iminfo.bytesPerRow; + final double ls = Math.log(s); - double h = 0; - for (int x : histog) { - if (x > 0) - h += (Math.log(x) + ls) * x; - } - h *= s * LOG2NI; - if (h < 0.0) - h = 0.0; - return h; - } + double h = 0; + for (final int x : histog) + if (x > 0) + h += (Math.log(x) + ls) * x; + h *= s * FiltersPerformance.LOG2NI; + if (h < 0.0) + h = 0.0; + return h; + } - /** - * If larger than 1.0, NONE will be more prefered. This must be called before init - * - * @param preferenceForNone around 1.0 (default: 1.0) - */ - public void setPreferenceForNone(double preferenceForNone) { - this.preferenceForNone = preferenceForNone; - } + /** + * If larger than 1.0, NONE will be more prefered. This must be called + * before init + * + * @param preferenceForNone + * around 1.0 (default: 1.0) + */ + public void setPreferenceForNone(final double preferenceForNone) { + this.preferenceForNone = preferenceForNone; + } - /** - * Values greater than 1.0 (towards infinite) increase the memory towards 1. Values smaller than 1.0 (towards zero) - * decreases the memory . - * - */ - public void tuneMemory(double m) { - if (m == 0) - memoryA = 0.0; - else - memoryA = Math.pow(memoryA, 1.0 / m); - } + /** + * Values greater than 1.0 (towards infinite) increase the memory towards 1. + * Values smaller than 1.0 (towards zero) + * decreases the memory . + * + */ + public void tuneMemory(final double m) { + if (m == 0) + memoryA = 0.0; + else + memoryA = Math.pow(memoryA, 1.0 / m); + } - /** - * To set manually the filter weights. This is not recommended, unless you know what you are doing. Setting this - * ignores preferenceForNone and omits some heuristics - * - * @param weights Five doubles around 1.0, one for each filter type. Lower is preferered - */ - public void setFilterWeights(double[] weights) { - System.arraycopy(weights, 0, filter_weights, 0, 5); - } + /** + * To set manually the filter weights. This is not recommended, unless you + * know what you are doing. Setting this + * ignores preferenceForNone and omits some heuristics + * + * @param weights + * Five doubles around 1.0, one for each filter type. Lower is + * preferered + */ + public void setFilterWeights(final double[] weights) { + System.arraycopy(weights, 0, filter_weights, 0, 5); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/pixels/PixelsWriter.java b/teavm/src/main/java/ar/com/hjg/pngj/pixels/PixelsWriter.java index 677cef1a..9ab95115 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/pixels/PixelsWriter.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/pixels/PixelsWriter.java @@ -10,254 +10,263 @@ import ar.com.hjg.pngj.PngHelperInternal; import ar.com.hjg.pngj.PngjOutputException; /** - * Encodes a set of rows (pixels) as a continuous deflated stream (does not know about IDAT chunk segmentation). + * Encodes a set of rows (pixels) as a continuous deflated stream (does not know + * about IDAT chunk segmentation). *

- * This includes the filter selection strategy, plus the filtering itself and the deflating. Only supports fixed length + * This includes the filter selection strategy, plus the filtering itself and + * the deflating. Only supports fixed length * rows (no interlaced writing). *

- * Typically an instance of this is hold by a PngWriter - but more instances could be used (for APGN) + * Typically an instance of this is hold by a PngWriter - but more instances + * could be used (for APGN) */ public abstract class PixelsWriter { - private static final int IDAT_MAX_SIZE_DEFAULT = 32000; + private static final int IDAT_MAX_SIZE_DEFAULT = 32000; - protected final ImageInfo imgInfo; - /** - * row buffer length, including filter byte (imgInfo.bytesPerRow + 1) - */ - protected final int buflen; + protected final ImageInfo imgInfo; + /** + * row buffer length, including filter byte (imgInfo.bytesPerRow + 1) + */ + protected final int buflen; - protected final int bytesPixel; - protected final int bytesRow; + protected final int bytesPixel; + protected final int bytesRow; - private CompressorStream compressorStream; // to compress the idat stream + private CompressorStream compressorStream; // to compress the idat stream - protected int deflaterCompLevel = 6; - protected int deflaterStrategy = Deflater.DEFAULT_STRATEGY; + protected int deflaterCompLevel = 6; + protected int deflaterStrategy = Deflater.DEFAULT_STRATEGY; - protected boolean initdone = false; + protected boolean initdone = false; - /** - * This is the globally configured filter type - it can be a concrete type or a pseudo type (hint or strategy) - */ - protected FilterType filterType; + /** + * This is the globally configured filter type - it can be a concrete type + * or a pseudo type (hint or strategy) + */ + protected FilterType filterType; - // counts the filters used - just for stats - private int[] filtersUsed = new int[5]; + // counts the filters used - just for stats + private final int[] filtersUsed = new int[5]; - // this is the raw underlying os (shared with the PngWriter) - private OutputStream os; + // this is the raw underlying os (shared with the PngWriter) + private OutputStream os; - private int idatMaxSize = IDAT_MAX_SIZE_DEFAULT; + private int idatMaxSize = PixelsWriter.IDAT_MAX_SIZE_DEFAULT; - /** - * row being processed, couting from zero - */ - protected int currentRow; + /** + * row being processed, couting from zero + */ + protected int currentRow; + public PixelsWriter(final ImageInfo imgInfo) { + this.imgInfo = imgInfo; + bytesRow = imgInfo.bytesPerRow; + buflen = bytesRow + 1; + bytesPixel = imgInfo.bytesPixel; + currentRow = -1; + filterType = FilterType.FILTER_DEFAULT; + } - public PixelsWriter(ImageInfo imgInfo) { - this.imgInfo = imgInfo; - bytesRow = imgInfo.bytesPerRow; - buflen = bytesRow + 1; - bytesPixel = imgInfo.bytesPixel; - currentRow = -1; - filterType = FilterType.FILTER_DEFAULT; - } + /** + * main internal point for external call. It does the lazy initializion if + * necessary, sets current row, and call + * {@link #filterAndWrite(byte[])} + */ + public final void processRow(final byte[] rowb) { + if (!initdone) + init(); + currentRow++; + filterAndWrite(rowb); + } - /** - * main internal point for external call. It does the lazy initializion if necessary, sets current row, and call - * {@link #filterAndWrite(byte[])} - */ - public final void processRow(final byte[] rowb) { - if (!initdone) - init(); - currentRow++; - filterAndWrite(rowb); - } + protected void sendToCompressedStream(final byte[] rowf) { + compressorStream.write(rowf, 0, rowf.length); + filtersUsed[rowf[0]]++; + } - protected void sendToCompressedStream(byte[] rowf) { - compressorStream.write(rowf, 0, rowf.length); - filtersUsed[rowf[0]]++; - } + /** + * This does the filtering and send to stream. Typically should decide the + * filtering, call + * {@link #filterRowWithFilterType(FilterType, byte[], byte[], byte[])} and + * and + * {@link #sendToCompressedStream(byte[])} + * + * @param rowb + */ + protected abstract void filterAndWrite(final byte[] rowb); - /** - * This does the filtering and send to stream. Typically should decide the filtering, call - * {@link #filterRowWithFilterType(FilterType, byte[], byte[], byte[])} and and - * {@link #sendToCompressedStream(byte[])} - * - * @param rowb - */ - protected abstract void filterAndWrite(final byte[] rowb); + /** + * Does the real filtering. This must be called with the real (standard) + * filterType. This should rarely be overriden. + *

+ * WARNING: look out the contract + * + * @param _filterType + * @param _rowb + * current row (the first byte might be modified) + * @param _rowbprev + * previous row (should be all zero the first time) + * @param _rowf + * tentative buffer to store the filtered bytes. might not be + * used! + * @return normally _rowf, but eventually _rowb. This MUST NOT BE MODIFIED + * nor reused by caller + */ + final protected byte[] filterRowWithFilterType(final FilterType _filterType, final byte[] _rowb, + final byte[] _rowbprev, byte[] _rowf) { + // warning: some filters rely on: "previous row" (rowbprev) it must be initialized to 0 the + // first time + if (_filterType == FilterType.FILTER_NONE) + _rowf = _rowb; + _rowf[0] = (byte) _filterType.val; + int i, j; + switch (_filterType) { + case FILTER_NONE: + // we return the same original (be careful!) + break; + case FILTER_PAETH: + for (i = 1; i <= bytesPixel; i++) + _rowf[i] = (byte) PngHelperInternal.filterRowPaeth(_rowb[i], 0, _rowbprev[i] & 0xFF, 0); + for (j = 1, i = bytesPixel + 1; i <= bytesRow; i++, j++) + _rowf[i] = (byte) PngHelperInternal.filterRowPaeth(_rowb[i], _rowb[j] & 0xFF, _rowbprev[i] & 0xFF, _rowbprev[j] & 0xFF); + break; + case FILTER_SUB: + for (i = 1; i <= bytesPixel; i++) + _rowf[i] = _rowb[i]; + for (j = 1, i = bytesPixel + 1; i <= bytesRow; i++, j++) + _rowf[i] = (byte) (_rowb[i] - _rowb[j]); + break; + case FILTER_AVERAGE: + for (i = 1; i <= bytesPixel; i++) + _rowf[i] = (byte) (_rowb[i] - (_rowbprev[i] & 0xFF) / 2); + for (j = 1, i = bytesPixel + 1; i <= bytesRow; i++, j++) + _rowf[i] = (byte) (_rowb[i] - ((_rowbprev[i] & 0xFF) + (_rowb[j] & 0xFF)) / 2); + break; + case FILTER_UP: + for (i = 1; i <= bytesRow; i++) + _rowf[i] = (byte) (_rowb[i] - _rowbprev[i]); + break; + default: + throw new PngjOutputException("Filter type not recognized: " + _filterType); + } + return _rowf; + } - /** - * Does the real filtering. This must be called with the real (standard) filterType. This should rarely be overriden. - *

- * WARNING: look out the contract - * - * @param _filterType - * @param _rowb current row (the first byte might be modified) - * @param _rowbprev previous row (should be all zero the first time) - * @param _rowf tentative buffer to store the filtered bytes. might not be used! - * @return normally _rowf, but eventually _rowb. This MUST NOT BE MODIFIED nor reused by caller - */ - final protected byte[] filterRowWithFilterType(FilterType _filterType, byte[] _rowb, - byte[] _rowbprev, byte[] _rowf) { - // warning: some filters rely on: "previous row" (rowbprev) it must be initialized to 0 the - // first time - if (_filterType == FilterType.FILTER_NONE) - _rowf = _rowb; - _rowf[0] = (byte) _filterType.val; - int i, j; - switch (_filterType) { - case FILTER_NONE: - // we return the same original (be careful!) - break; - case FILTER_PAETH: - for (i = 1; i <= bytesPixel; i++) - _rowf[i] = (byte) PngHelperInternal.filterRowPaeth(_rowb[i], 0, _rowbprev[i] & 0xFF, 0); - for (j = 1, i = bytesPixel + 1; i <= bytesRow; i++, j++) - _rowf[i] = - (byte) PngHelperInternal.filterRowPaeth(_rowb[i], _rowb[j] & 0xFF, - _rowbprev[i] & 0xFF, _rowbprev[j] & 0xFF); - break; - case FILTER_SUB: - for (i = 1; i <= bytesPixel; i++) - _rowf[i] = (byte) _rowb[i]; - for (j = 1, i = bytesPixel + 1; i <= bytesRow; i++, j++) - _rowf[i] = (byte) (_rowb[i] - _rowb[j]); - break; - case FILTER_AVERAGE: - for (i = 1; i <= bytesPixel; i++) - _rowf[i] = (byte) (_rowb[i] - (_rowbprev[i] & 0xFF) / 2); - for (j = 1, i = bytesPixel + 1; i <= bytesRow; i++, j++) - _rowf[i] = (byte) (_rowb[i] - ((_rowbprev[i] & 0xFF) + (_rowb[j] & 0xFF)) / 2); - break; - case FILTER_UP: - for (i = 1; i <= bytesRow; i++) - _rowf[i] = (byte) (_rowb[i] - _rowbprev[i]); - break; - default: - throw new PngjOutputException("Filter type not recognized: " + _filterType); - } - return _rowf; - } + /** + * This will be called by the PngWrite to fill the raw pixels for each row. + * This can change from call to call. + * Warning: this can be called before the object is init, implementations + * should call init() to be sure + */ + public abstract byte[] getRowb(); - /** - * This will be called by the PngWrite to fill the raw pixels for each row. This can change from call to call. - * Warning: this can be called before the object is init, implementations should call init() to be sure - */ - public abstract byte[] getRowb(); + /** + * This will be called lazily just before writing row 0. Idempotent. + */ + protected final void init() { + if (!initdone) { + initParams(); + initdone = true; + } + } - /** - * This will be called lazily just before writing row 0. Idempotent. - */ - protected final void init() { - if (!initdone) { - initParams(); - initdone = true; - } - } + /** + * called by init(); override (calling this first) to do additional + * initialization + */ + protected void initParams() { + final IDatChunkWriter idatWriter = new IDatChunkWriter(os, idatMaxSize); + if (compressorStream == null) + compressorStream = new CompressorStreamDeflater(idatWriter, buflen, imgInfo.getTotalRawBytes(), deflaterCompLevel, deflaterStrategy); + } - /** called by init(); override (calling this first) to do additional initialization */ - protected void initParams() { - IDatChunkWriter idatWriter = new IDatChunkWriter(os, idatMaxSize); - if (compressorStream == null) { // if not set, use the deflater - compressorStream = - new CompressorStreamDeflater(idatWriter, buflen, imgInfo.getTotalRawBytes(), - deflaterCompLevel, deflaterStrategy); - } - } + /** cleanup. This should be called explicitly. Idempotent and secure */ + public void close() { + if (compressorStream != null) + compressorStream.close(); + } - /** cleanup. This should be called explicitly. Idempotent and secure */ - public void close() { - if (compressorStream != null) { - compressorStream.close(); - } - } + /** + * Deflater (ZLIB) strategy. You should rarely change this from the default + * (Deflater.DEFAULT_STRATEGY) to + * Deflater.FILTERED (Deflater.HUFFMAN_ONLY is fast but compress poorly) + */ + public void setDeflaterStrategy(final Integer deflaterStrategy) { + this.deflaterStrategy = deflaterStrategy; + } - /** - * Deflater (ZLIB) strategy. You should rarely change this from the default (Deflater.DEFAULT_STRATEGY) to - * Deflater.FILTERED (Deflater.HUFFMAN_ONLY is fast but compress poorly) - */ - public void setDeflaterStrategy(Integer deflaterStrategy) { - this.deflaterStrategy = deflaterStrategy; - } + /** + * Deflater (ZLIB) compression level, between 0 (no compression) and 9 + */ + public void setDeflaterCompLevel(final Integer deflaterCompLevel) { + this.deflaterCompLevel = deflaterCompLevel; + } - /** - * Deflater (ZLIB) compression level, between 0 (no compression) and 9 - */ - public void setDeflaterCompLevel(Integer deflaterCompLevel) { - this.deflaterCompLevel = deflaterCompLevel; - } + public Integer getDeflaterCompLevel() { + return deflaterCompLevel; + } - public Integer getDeflaterCompLevel() { - return deflaterCompLevel; - } + public final void setOs(final OutputStream datStream) { + os = datStream; + } + public OutputStream getOs() { + return os; + } - public final void setOs(OutputStream datStream) { - this.os = datStream; - } + /** @see #filterType */ + final public FilterType getFilterType() { + return filterType; + } - public OutputStream getOs() { - return os; - } + /** @see #filterType */ + final public void setFilterType(final FilterType filterType) { + this.filterType = filterType; + } - /** @see #filterType */ - final public FilterType getFilterType() { - return filterType; - } + /* out/in This should be called only after end() to get reliable results */ + public double getCompression() { + return compressorStream.isDone() ? compressorStream.getCompressionRatio() : 1.0; + } - /** @see #filterType */ - final public void setFilterType(FilterType filterType) { - this.filterType = filterType; - } + public void setCompressorStream(final CompressorStream compressorStream) { + this.compressorStream = compressorStream; + } - /* out/in This should be called only after end() to get reliable results */ - public double getCompression() { - return compressorStream.isDone() ? compressorStream.getCompressionRatio() : 1.0; - } + public long getTotalBytesToWrite() { + return imgInfo.getTotalRawBytes(); + } - public void setCompressorStream(CompressorStream compressorStream) { - this.compressorStream = compressorStream; - } + public boolean isDone() { + return currentRow == imgInfo.rows - 1; + } - public long getTotalBytesToWrite() { - return imgInfo.getTotalRawBytes(); - } + /** + * computed default fixed filter type to use, if specified DEFAULT; wilde + * guess based on image properties + * + * @return One of the five concrete filter types + */ + protected FilterType getDefaultFilter() { + if (imgInfo.indexed || imgInfo.bitDepth < 8) + return FilterType.FILTER_NONE; + else if (imgInfo.getTotalPixels() < 1024) + return FilterType.FILTER_NONE; + else if (imgInfo.rows == 1) + return FilterType.FILTER_SUB; + else if (imgInfo.cols == 1) + return FilterType.FILTER_UP; + else + return FilterType.FILTER_PAETH; + } - public boolean isDone() { - return currentRow == imgInfo.rows - 1; - } + /** informational stats : filter used, in percentages */ + final public String getFiltersUsed() { + return String.format("%d,%d,%d,%d,%d", (int) (filtersUsed[0] * 100.0 / imgInfo.rows + 0.5), (int) (filtersUsed[1] * 100.0 / imgInfo.rows + 0.5), (int) (filtersUsed[2] * 100.0 / imgInfo.rows + 0.5), (int) (filtersUsed[3] * 100.0 / imgInfo.rows + 0.5), (int) (filtersUsed[4] * 100.0 / imgInfo.rows + 0.5)); + } - /** - * computed default fixed filter type to use, if specified DEFAULT; wilde guess based on image properties - * - * @return One of the five concrete filter types - */ - protected FilterType getDefaultFilter() { - if (imgInfo.indexed || imgInfo.bitDepth < 8) - return FilterType.FILTER_NONE; - else if (imgInfo.getTotalPixels() < 1024) - return FilterType.FILTER_NONE; - else if (imgInfo.rows == 1) - return FilterType.FILTER_SUB; - else if (imgInfo.cols == 1) - return FilterType.FILTER_UP; - else - return FilterType.FILTER_PAETH; - } - - /** informational stats : filter used, in percentages */ - final public String getFiltersUsed() { - return String.format("%d,%d,%d,%d,%d", (int) (filtersUsed[0] * 100.0 / imgInfo.rows + 0.5), - (int) (filtersUsed[1] * 100.0 / imgInfo.rows + 0.5), (int) (filtersUsed[2] * 100.0 - / imgInfo.rows + 0.5), (int) (filtersUsed[3] * 100.0 / imgInfo.rows + 0.5), - (int) (filtersUsed[4] * 100.0 / imgInfo.rows + 0.5)); - } - - public void setIdatMaxSize(int idatMaxSize) { - this.idatMaxSize = idatMaxSize; - } + public void setIdatMaxSize(final int idatMaxSize) { + this.idatMaxSize = idatMaxSize; + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/pixels/PixelsWriterDefault.java b/teavm/src/main/java/ar/com/hjg/pngj/pixels/PixelsWriterDefault.java index 5b8752a6..00ffcec9 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/pixels/PixelsWriterDefault.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/pixels/PixelsWriterDefault.java @@ -7,152 +7,152 @@ import ar.com.hjg.pngj.ImageInfo; import ar.com.hjg.pngj.PngjOutputException; /** - * Default implementation of PixelsWriter, with fixed filters and also adaptive strategies. + * Default implementation of PixelsWriter, with fixed filters and also adaptive + * strategies. */ public class PixelsWriterDefault extends PixelsWriter { - /** current raw row */ - protected byte[] rowb; - /** previous raw row */ - protected byte[] rowbprev; - /** buffer for filtered row */ - protected byte[] rowbfilter; + /** current raw row */ + protected byte[] rowb; + /** previous raw row */ + protected byte[] rowbprev; + /** buffer for filtered row */ + protected byte[] rowbfilter; - /** evaluates different filters, for adaptive strategy */ - protected FiltersPerformance filtersPerformance; + /** evaluates different filters, for adaptive strategy */ + protected FiltersPerformance filtersPerformance; - /** currently concrete selected filter type */ - protected FilterType curfilterType; + /** currently concrete selected filter type */ + protected FilterType curfilterType; - /** parameters for adaptive strategy */ - protected int adaptMaxSkip; // set in initParams, does not change - protected int adaptSkipIncreaseSinceRow; // set in initParams, does not change - protected double adaptSkipIncreaseFactor; // set in initParams, does not change - protected int adaptNextRow = 0; + /** parameters for adaptive strategy */ + protected int adaptMaxSkip; // set in initParams, does not change + protected int adaptSkipIncreaseSinceRow; // set in initParams, does not change + protected double adaptSkipIncreaseFactor; // set in initParams, does not change + protected int adaptNextRow = 0; - public PixelsWriterDefault(ImageInfo imgInfo) { - super(imgInfo); - filtersPerformance = new FiltersPerformance(imgInfo); - } + public PixelsWriterDefault(final ImageInfo imgInfo) { + super(imgInfo); + filtersPerformance = new FiltersPerformance(imgInfo); + } - @Override - protected void initParams() { - super.initParams(); + @Override + protected void initParams() { + super.initParams(); - if (rowb == null || rowb.length < buflen) - rowb = new byte[buflen]; - if (rowbfilter == null || rowbfilter.length < buflen) - rowbfilter = new byte[buflen]; - if (rowbprev == null || rowbprev.length < buflen) - rowbprev = new byte[buflen]; - else - Arrays.fill(rowbprev, (byte) 0); + if (rowb == null || rowb.length < buflen) + rowb = new byte[buflen]; + if (rowbfilter == null || rowbfilter.length < buflen) + rowbfilter = new byte[buflen]; + if (rowbprev == null || rowbprev.length < buflen) + rowbprev = new byte[buflen]; + else + Arrays.fill(rowbprev, (byte) 0); - // if adaptative but too few rows or columns, use default - if (imgInfo.cols < 3 && !FilterType.isValidStandard(filterType)) - filterType = FilterType.FILTER_DEFAULT; - if (imgInfo.rows < 3 && !FilterType.isValidStandard(filterType)) - filterType = FilterType.FILTER_DEFAULT; + // if adaptative but too few rows or columns, use default + if (imgInfo.cols < 3 && !FilterType.isValidStandard(filterType)) + filterType = FilterType.FILTER_DEFAULT; + if (imgInfo.rows < 3 && !FilterType.isValidStandard(filterType)) + filterType = FilterType.FILTER_DEFAULT; - if (imgInfo.getTotalPixels() <= 1024 && !FilterType.isValidStandard(filterType)) - filterType = getDefaultFilter(); + if (imgInfo.getTotalPixels() <= 1024 && !FilterType.isValidStandard(filterType)) + filterType = getDefaultFilter(); - if (FilterType.isAdaptive(filterType)) { - // adaptCurSkip = 0; - adaptNextRow = 0; - if (filterType == FilterType.FILTER_ADAPTIVE_FAST) { - adaptMaxSkip = 200; - adaptSkipIncreaseSinceRow = 3; - adaptSkipIncreaseFactor = 1 / 4.0; // skip ~ row/3 - } else if (filterType == FilterType.FILTER_ADAPTIVE_MEDIUM) { - adaptMaxSkip = 8; - adaptSkipIncreaseSinceRow = 32; - adaptSkipIncreaseFactor = 1 / 80.0; - } else if (filterType == FilterType.FILTER_ADAPTIVE_FULL) { - adaptMaxSkip = 0; - adaptSkipIncreaseSinceRow = 128; - adaptSkipIncreaseFactor = 1 / 120.0; - } else - throw new PngjOutputException("bad filter " + filterType); - } - } + if (FilterType.isAdaptive(filterType)) { + // adaptCurSkip = 0; + adaptNextRow = 0; + if (filterType == FilterType.FILTER_ADAPTIVE_FAST) { + adaptMaxSkip = 200; + adaptSkipIncreaseSinceRow = 3; + adaptSkipIncreaseFactor = 1 / 4.0; // skip ~ row/3 + } else if (filterType == FilterType.FILTER_ADAPTIVE_MEDIUM) { + adaptMaxSkip = 8; + adaptSkipIncreaseSinceRow = 32; + adaptSkipIncreaseFactor = 1 / 80.0; + } else if (filterType == FilterType.FILTER_ADAPTIVE_FULL) { + adaptMaxSkip = 0; + adaptSkipIncreaseSinceRow = 128; + adaptSkipIncreaseFactor = 1 / 120.0; + } else + throw new PngjOutputException("bad filter " + filterType); + } + } - @Override - protected void filterAndWrite(final byte[] rowb) { - if (rowb != this.rowb) - throw new RuntimeException("??"); // we rely on this - decideCurFilterType(); - byte[] filtered = filterRowWithFilterType(curfilterType, rowb, rowbprev, rowbfilter); - sendToCompressedStream(filtered); - // swap rowb <-> rowbprev - byte[] aux = this.rowb; - this.rowb = rowbprev; - rowbprev = aux; - } + @Override + protected void filterAndWrite(final byte[] rowb) { + if (rowb != this.rowb) + throw new RuntimeException("??"); // we rely on this + decideCurFilterType(); + final byte[] filtered = filterRowWithFilterType(curfilterType, rowb, rowbprev, rowbfilter); + sendToCompressedStream(filtered); + // swap rowb <-> rowbprev + final byte[] aux = this.rowb; + this.rowb = rowbprev; + rowbprev = aux; + } - protected void decideCurFilterType() { - // decide the real filter and store in curfilterType - if (FilterType.isValidStandard(getFilterType())) { - curfilterType = getFilterType(); - } else if (getFilterType() == FilterType.FILTER_PRESERVE) { - curfilterType = FilterType.getByVal(rowb[0]); - } else if (getFilterType() == FilterType.FILTER_CYCLIC) { - curfilterType = FilterType.getByVal(currentRow % 5); - } else if (getFilterType() == FilterType.FILTER_DEFAULT) { - setFilterType(getDefaultFilter()); - curfilterType = getFilterType(); // this could be done once - } else if (FilterType.isAdaptive(getFilterType())) {// adaptive - if (currentRow == adaptNextRow) { - for (FilterType ftype : FilterType.getAllStandard()) - filtersPerformance.updateFromRaw(ftype, rowb, rowbprev, currentRow); - curfilterType = filtersPerformance.getPreferred(); - int skip = - (currentRow >= adaptSkipIncreaseSinceRow ? (int) Math - .round((currentRow - adaptSkipIncreaseSinceRow) * adaptSkipIncreaseFactor) : 0); - if (skip > adaptMaxSkip) - skip = adaptMaxSkip; - if (currentRow == 0) - skip = 0; - adaptNextRow = currentRow + 1 + skip; - } - } else { - throw new PngjOutputException("not implemented filter: " + getFilterType()); - } - if (currentRow == 0 && curfilterType != FilterType.FILTER_NONE - && curfilterType != FilterType.FILTER_SUB) - curfilterType = FilterType.FILTER_SUB; // first row should always be none or sub - } + protected void decideCurFilterType() { + // decide the real filter and store in curfilterType + if (FilterType.isValidStandard(getFilterType())) + curfilterType = getFilterType(); + else if (getFilterType() == FilterType.FILTER_PRESERVE) + curfilterType = FilterType.getByVal(rowb[0]); + else if (getFilterType() == FilterType.FILTER_CYCLIC) + curfilterType = FilterType.getByVal(currentRow % 5); + else if (getFilterType() == FilterType.FILTER_DEFAULT) { + setFilterType(getDefaultFilter()); + curfilterType = getFilterType(); // this could be done once + } else if (FilterType.isAdaptive(getFilterType())) {// adaptive + if (currentRow == adaptNextRow) { + for (final FilterType ftype : FilterType.getAllStandard()) + filtersPerformance.updateFromRaw(ftype, rowb, rowbprev, currentRow); + curfilterType = filtersPerformance.getPreferred(); + int skip = currentRow >= adaptSkipIncreaseSinceRow ? (int) Math.round((currentRow - adaptSkipIncreaseSinceRow) * adaptSkipIncreaseFactor) : 0; + if (skip > adaptMaxSkip) + skip = adaptMaxSkip; + if (currentRow == 0) + skip = 0; + adaptNextRow = currentRow + 1 + skip; + } + } else + throw new PngjOutputException("not implemented filter: " + getFilterType()); + if (currentRow == 0 && curfilterType != FilterType.FILTER_NONE && curfilterType != FilterType.FILTER_SUB) + curfilterType = FilterType.FILTER_SUB; // first row should always be none or sub + } - @Override - public byte[] getRowb() { - if (!initdone) - init(); - return rowb; - } + @Override + public byte[] getRowb() { + if (!initdone) + init(); + return rowb; + } - @Override - public void close() { - super.close(); - } + @Override + public void close() { + super.close(); + } - /** - * Only for adaptive strategies. See {@link FiltersPerformance#setPreferenceForNone(double)} - */ - public void setPreferenceForNone(double preferenceForNone) { - filtersPerformance.setPreferenceForNone(preferenceForNone); - } + /** + * Only for adaptive strategies. See + * {@link FiltersPerformance#setPreferenceForNone(double)} + */ + public void setPreferenceForNone(final double preferenceForNone) { + filtersPerformance.setPreferenceForNone(preferenceForNone); + } - /** - * Only for adaptive strategies. See {@link FiltersPerformance#tuneMemory(double)} - */ - public void tuneMemory(double m) { - filtersPerformance.tuneMemory(m); - } + /** + * Only for adaptive strategies. See + * {@link FiltersPerformance#tuneMemory(double)} + */ + public void tuneMemory(final double m) { + filtersPerformance.tuneMemory(m); + } - /** - * Only for adaptive strategies. See {@link FiltersPerformance#setFilterWeights(double[])} - */ - public void setFilterWeights(double[] weights) { - filtersPerformance.setFilterWeights(weights); - } + /** + * Only for adaptive strategies. See + * {@link FiltersPerformance#setFilterWeights(double[])} + */ + public void setFilterWeights(final double[] weights) { + filtersPerformance.setFilterWeights(weights); + } } diff --git a/teavm/src/main/java/ar/com/hjg/pngj/pixels/PixelsWriterMultiple.java b/teavm/src/main/java/ar/com/hjg/pngj/pixels/PixelsWriterMultiple.java index 367dd981..bf36c12b 100644 --- a/teavm/src/main/java/ar/com/hjg/pngj/pixels/PixelsWriterMultiple.java +++ b/teavm/src/main/java/ar/com/hjg/pngj/pixels/PixelsWriterMultiple.java @@ -8,234 +8,223 @@ import ar.com.hjg.pngj.ImageInfo; /** Special pixels writer for experimental super adaptive strategy */ public class PixelsWriterMultiple extends PixelsWriter { - /** - * unfiltered rowsperband elements, 0 is the current (rowb). This should include all rows of current band, plus one - */ - protected LinkedList rows; + /** + * unfiltered rowsperband elements, 0 is the current (rowb). This should + * include all rows of current band, plus one + */ + protected LinkedList rows; - /** - * bank of compressor estimators, one for each filter and (perhaps) an adaptive strategy - */ - protected CompressorStream[] filterBank = new CompressorStream[6]; - /** - * stored filtered rows, one for each filter (0=none is not allocated but linked) - */ - protected byte[][] filteredRows = new byte[5][]; - protected byte[] filteredRowTmp; // + /** + * bank of compressor estimators, one for each filter and (perhaps) an + * adaptive strategy + */ + protected CompressorStream[] filterBank = new CompressorStream[6]; + /** + * stored filtered rows, one for each filter (0=none is not allocated but + * linked) + */ + protected byte[][] filteredRows = new byte[5][]; + protected byte[] filteredRowTmp; // - protected FiltersPerformance filtersPerf; - protected int rowsPerBand = 0; // This is a 'nominal' size - protected int rowsPerBandCurrent = 0; // lastRowInThisBand-firstRowInThisBand +1 : might be - // smaller than rowsPerBand - protected int rowInBand = -1; - protected int bandNum = -1; - protected int firstRowInThisBand, lastRowInThisBand; - private boolean tryAdaptive = true; + protected FiltersPerformance filtersPerf; + protected int rowsPerBand = 0; // This is a 'nominal' size + protected int rowsPerBandCurrent = 0; // lastRowInThisBand-firstRowInThisBand +1 : might be + // smaller than rowsPerBand + protected int rowInBand = -1; + protected int bandNum = -1; + protected int firstRowInThisBand, lastRowInThisBand; + private boolean tryAdaptive = true; - protected static final int HINT_MEMORY_DEFAULT_KB = 100; - // we will consume about (not more than) this memory (in buffers, not counting the compressors) - protected int hintMemoryKb = HINT_MEMORY_DEFAULT_KB; + protected static final int HINT_MEMORY_DEFAULT_KB = 100; + // we will consume about (not more than) this memory (in buffers, not counting the compressors) + protected int hintMemoryKb = PixelsWriterMultiple.HINT_MEMORY_DEFAULT_KB; - private int hintRowsPerBand = 1000; // default: very large number, can be changed + private int hintRowsPerBand = 1000; // default: very large number, can be changed - private boolean useLz4 = true; + private boolean useLz4 = true; - public PixelsWriterMultiple(ImageInfo imgInfo) { - super(imgInfo); - filtersPerf = new FiltersPerformance(imgInfo); - rows = new LinkedList(); - for (int i = 0; i < 2; i++) - rows.add(new byte[buflen]); // we preallocate 2 rows (rowb and rowbprev) - filteredRowTmp = new byte[buflen]; - } + public PixelsWriterMultiple(final ImageInfo imgInfo) { + super(imgInfo); + filtersPerf = new FiltersPerformance(imgInfo); + rows = new LinkedList<>(); + for (int i = 0; i < 2; i++) + rows.add(new byte[buflen]); // we preallocate 2 rows (rowb and rowbprev) + filteredRowTmp = new byte[buflen]; + } - @Override - protected void filterAndWrite(byte[] rowb) { - if (!initdone) - init(); - if (rowb != rows.get(0)) - throw new RuntimeException("?"); - setBandFromNewRown(); - byte[] rowbprev = rows.get(1); - for (FilterType ftype : FilterType.getAllStandardNoneLast()) { - // this has a special behaviour for NONE: filteredRows[0] is null, and the returned value is - // rowb - if (currentRow == 0 && ftype != FilterType.FILTER_NONE && ftype != FilterType.FILTER_SUB) - continue; - byte[] filtered = filterRowWithFilterType(ftype, rowb, rowbprev, filteredRows[ftype.val]); - filterBank[ftype.val].write(filtered); - if (currentRow == 0 && ftype == FilterType.FILTER_SUB) { // litle lie, only for first row - filterBank[FilterType.FILTER_PAETH.val].write(filtered); - filterBank[FilterType.FILTER_AVERAGE.val].write(filtered); - filterBank[FilterType.FILTER_UP.val].write(filtered); - } - // adptive: report each filterted - if (tryAdaptive) { - filtersPerf.updateFromFiltered(ftype, filtered, currentRow); - } - } - filteredRows[0] = rowb; - if (tryAdaptive) { - FilterType preferredAdaptive = filtersPerf.getPreferred(); - filterBank[5].write(filteredRows[preferredAdaptive.val]); - } - if (currentRow == lastRowInThisBand) { - int best = getBestCompressor(); - // PngHelperInternal.debug("won: " + best + " (rows: " + firstRowInThisBand + ":" + lastRowInThisBand + ")"); - // if(currentRow>90&¤tRow<100) - // PngHelperInternal.debug(String.format("row=%d ft=%s",currentRow,FilterType.getByVal(best))); - byte[] filtersAdapt = filterBank[best].getFirstBytes(); - for (int r = firstRowInThisBand, i = 0, j = lastRowInThisBand - firstRowInThisBand; r <= lastRowInThisBand; r++, j--, i++) { - int fti = filtersAdapt[i]; - byte[] filtered = null; - if (r != lastRowInThisBand) { - filtered = - filterRowWithFilterType(FilterType.getByVal(fti), rows.get(j), rows.get(j + 1), - filteredRowTmp); - } else { // no need to do this filtering, we already have it - filtered = filteredRows[fti]; - } - sendToCompressedStream(filtered); - } - } - // rotate - if (rows.size() > rowsPerBandCurrent) { - rows.addFirst(rows.removeLast()); - } else - rows.addFirst(new byte[buflen]); - } + @Override + protected void filterAndWrite(final byte[] rowb) { + if (!initdone) + init(); + if (rowb != rows.get(0)) + throw new RuntimeException("?"); + setBandFromNewRown(); + final byte[] rowbprev = rows.get(1); + for (final FilterType ftype : FilterType.getAllStandardNoneLast()) { + // this has a special behaviour for NONE: filteredRows[0] is null, and the returned value is + // rowb + if (currentRow == 0 && ftype != FilterType.FILTER_NONE && ftype != FilterType.FILTER_SUB) + continue; + final byte[] filtered = filterRowWithFilterType(ftype, rowb, rowbprev, filteredRows[ftype.val]); + filterBank[ftype.val].write(filtered); + if (currentRow == 0 && ftype == FilterType.FILTER_SUB) { // litle lie, only for first row + filterBank[FilterType.FILTER_PAETH.val].write(filtered); + filterBank[FilterType.FILTER_AVERAGE.val].write(filtered); + filterBank[FilterType.FILTER_UP.val].write(filtered); + } + // adptive: report each filterted + if (tryAdaptive) + filtersPerf.updateFromFiltered(ftype, filtered, currentRow); + } + filteredRows[0] = rowb; + if (tryAdaptive) { + final FilterType preferredAdaptive = filtersPerf.getPreferred(); + filterBank[5].write(filteredRows[preferredAdaptive.val]); + } + if (currentRow == lastRowInThisBand) { + final int best = getBestCompressor(); + // PngHelperInternal.debug("won: " + best + " (rows: " + firstRowInThisBand + ":" + lastRowInThisBand + ")"); + // if(currentRow>90&¤tRow<100) + // PngHelperInternal.debug(String.format("row=%d ft=%s",currentRow,FilterType.getByVal(best))); + final byte[] filtersAdapt = filterBank[best].getFirstBytes(); + for (int r = firstRowInThisBand, i = 0, j = lastRowInThisBand - firstRowInThisBand; r <= lastRowInThisBand; r++, j--, i++) { + final int fti = filtersAdapt[i]; + byte[] filtered = null; + if (r != lastRowInThisBand) + filtered = filterRowWithFilterType(FilterType.getByVal(fti), rows.get(j), rows.get(j + 1), filteredRowTmp); + else + filtered = filteredRows[fti]; + sendToCompressedStream(filtered); + } + } + // rotate + if (rows.size() > rowsPerBandCurrent) + rows.addFirst(rows.removeLast()); + else + rows.addFirst(new byte[buflen]); + } - @Override - public byte[] getRowb() { - return rows.get(0); - } + @Override + public byte[] getRowb() { + return rows.get(0); + } + private void setBandFromNewRown() { + final boolean newBand = currentRow == 0 || currentRow > lastRowInThisBand; + if (currentRow == 0) + bandNum = -1; + if (newBand) { + bandNum++; + rowInBand = 0; + } else + rowInBand++; + if (newBand) { + firstRowInThisBand = currentRow; + lastRowInThisBand = firstRowInThisBand + rowsPerBand - 1; + final int lastRowInNextBand = firstRowInThisBand + 2 * rowsPerBand - 1; + if (lastRowInNextBand >= imgInfo.rows) // hack:make this band bigger, so we don't have a small + // last band + lastRowInThisBand = imgInfo.rows - 1; + rowsPerBandCurrent = 1 + lastRowInThisBand - firstRowInThisBand; + tryAdaptive = rowsPerBandCurrent <= 3 || rowsPerBandCurrent < 10 && imgInfo.bytesPerRow < 64 ? false : true; + // rebuild bank + rebuildFiltersBank(); + } + } - private void setBandFromNewRown() { - boolean newBand = currentRow == 0 || currentRow > lastRowInThisBand; - if (currentRow == 0) - bandNum = -1; - if (newBand) { - bandNum++; - rowInBand = 0; - } else { - rowInBand++; - } - if (newBand) { - firstRowInThisBand = currentRow; - lastRowInThisBand = firstRowInThisBand + rowsPerBand - 1; - int lastRowInNextBand = firstRowInThisBand + 2 * rowsPerBand - 1; - if (lastRowInNextBand >= imgInfo.rows) // hack:make this band bigger, so we don't have a small - // last band - lastRowInThisBand = imgInfo.rows - 1; - rowsPerBandCurrent = 1 + lastRowInThisBand - firstRowInThisBand; - tryAdaptive = - rowsPerBandCurrent <= 3 || (rowsPerBandCurrent < 10 && imgInfo.bytesPerRow < 64) ? false - : true; - // rebuild bank - rebuildFiltersBank(); - } - } + private void rebuildFiltersBank() { + final long bytesPerBandCurrent = rowsPerBandCurrent * (long) buflen; + final int DEFLATER_COMP_LEVEL = 4; + for (int i = 0; i <= 5; i++) {// one for each filter plus one adaptive + CompressorStream cp = filterBank[i]; + if (cp == null || cp.totalbytes != bytesPerBandCurrent) { + if (cp != null) + cp.close(); + if (useLz4) + cp = new CompressorStreamLz4(null, buflen, bytesPerBandCurrent); + else + cp = new CompressorStreamDeflater(null, buflen, bytesPerBandCurrent, DEFLATER_COMP_LEVEL, Deflater.DEFAULT_STRATEGY); + filterBank[i] = cp; + } else + cp.reset(); + cp.setStoreFirstByte(true, rowsPerBandCurrent); // TODO: only for adaptive? + } + } - private void rebuildFiltersBank() { - long bytesPerBandCurrent = rowsPerBandCurrent * (long) buflen; - final int DEFLATER_COMP_LEVEL = 4; - for (int i = 0; i <= 5; i++) {// one for each filter plus one adaptive - CompressorStream cp = filterBank[i]; - if (cp == null || cp.totalbytes != bytesPerBandCurrent) { - if (cp != null) - cp.close(); - if (useLz4) - cp = new CompressorStreamLz4(null, buflen, bytesPerBandCurrent); - else - cp = - new CompressorStreamDeflater(null, buflen, bytesPerBandCurrent, DEFLATER_COMP_LEVEL, - Deflater.DEFAULT_STRATEGY); - filterBank[i] = cp; - } else { - cp.reset(); - } - cp.setStoreFirstByte(true, rowsPerBandCurrent); // TODO: only for adaptive? - } - } + private int computeInitialRowsPerBand() { + // memory (only buffers) ~ (r+1+5) * bytesPerRow + int r = (int) (hintMemoryKb * 1024.0 / (imgInfo.bytesPerRow + 1) - 5); + if (r < 1) + r = 1; + if (hintRowsPerBand > 0 && r > hintRowsPerBand) + r = hintRowsPerBand; + if (r > imgInfo.rows) + r = imgInfo.rows; + if (r > 2 && r > imgInfo.rows / 8) { // redistribute more evenly + final int k = (imgInfo.rows + r - 1) / r; + r = (imgInfo.rows + k / 2) / k; + } + // PngHelperInternal.debug("rows :" + r + "/" + imgInfo.rows); + return r; + } - private int computeInitialRowsPerBand() { - // memory (only buffers) ~ (r+1+5) * bytesPerRow - int r = (int) ((hintMemoryKb * 1024.0) / (imgInfo.bytesPerRow + 1) - 5); - if (r < 1) - r = 1; - if (hintRowsPerBand > 0 && r > hintRowsPerBand) - r = hintRowsPerBand; - if (r > imgInfo.rows) - r = imgInfo.rows; - if (r > 2 && r > imgInfo.rows / 8) { // redistribute more evenly - int k = (imgInfo.rows + (r - 1)) / r; - r = (imgInfo.rows + k / 2) / k; - } - // PngHelperInternal.debug("rows :" + r + "/" + imgInfo.rows); - return r; - } + private int getBestCompressor() { + double bestcr = Double.MAX_VALUE; + int bestb = -1; + for (int i = tryAdaptive ? 5 : 4; i >= 0; i--) { + final CompressorStream fb = filterBank[i]; + final double cr = fb.getCompressionRatio(); + if (cr <= bestcr) { // dirty trick, here the equality gains for row 0, so that SUB is prefered + // over PAETH, UP, AVE... + bestb = i; + bestcr = cr; + } + } + return bestb; + } - private int getBestCompressor() { - double bestcr = Double.MAX_VALUE; - int bestb = -1; - for (int i = tryAdaptive ? 5 : 4; i >= 0; i--) { - CompressorStream fb = filterBank[i]; - double cr = fb.getCompressionRatio(); - if (cr <= bestcr) { // dirty trick, here the equality gains for row 0, so that SUB is prefered - // over PAETH, UP, AVE... - bestb = i; - bestcr = cr; - } - } - return bestb; - } + @Override + protected void initParams() { + super.initParams(); + // if adaptative but too few rows or columns, use default + if (imgInfo.cols < 3 && !FilterType.isValidStandard(filterType)) + filterType = FilterType.FILTER_DEFAULT; + if (imgInfo.rows < 3 && !FilterType.isValidStandard(filterType)) + filterType = FilterType.FILTER_DEFAULT; + for (int i = 1; i <= 4; i++) + if (filteredRows[i] == null || filteredRows[i].length < buflen) + filteredRows[i] = new byte[buflen]; + if (rowsPerBand == 0) + rowsPerBand = computeInitialRowsPerBand(); + } - @Override - protected void initParams() { - super.initParams(); - // if adaptative but too few rows or columns, use default - if (imgInfo.cols < 3 && !FilterType.isValidStandard(filterType)) - filterType = FilterType.FILTER_DEFAULT; - if (imgInfo.rows < 3 && !FilterType.isValidStandard(filterType)) - filterType = FilterType.FILTER_DEFAULT; - for (int i = 1; i <= 4; i++) { // element 0 is not allocated - if (filteredRows[i] == null || filteredRows[i].length < buflen) - filteredRows[i] = new byte[buflen]; - } - if (rowsPerBand == 0) - rowsPerBand = computeInitialRowsPerBand(); - } + @Override + public void close() { + super.close(); + rows.clear(); + for (final CompressorStream f : filterBank) + f.close(); + } - @Override - public void close() { - super.close(); - rows.clear(); - for (CompressorStream f : filterBank) { - f.close(); - } - } + public void setHintMemoryKb(final int hintMemoryKb) { + this.hintMemoryKb = hintMemoryKb <= 0 ? PixelsWriterMultiple.HINT_MEMORY_DEFAULT_KB : hintMemoryKb > 10000 ? 10000 : hintMemoryKb; + } - public void setHintMemoryKb(int hintMemoryKb) { - this.hintMemoryKb = - hintMemoryKb <= 0 ? HINT_MEMORY_DEFAULT_KB : (hintMemoryKb > 10000 ? 10000 : hintMemoryKb); - } + public void setHintRowsPerBand(final int hintRowsPerBand) { + this.hintRowsPerBand = hintRowsPerBand; + } - public void setHintRowsPerBand(int hintRowsPerBand) { - this.hintRowsPerBand = hintRowsPerBand; - } + public void setUseLz4(final boolean lz4) { + useLz4 = lz4; + } - public void setUseLz4(boolean lz4) { - this.useLz4 = lz4; - } + /** for tuning memory or other parameters */ + public FiltersPerformance getFiltersPerf() { + return filtersPerf; + } - /** for tuning memory or other parameters */ - public FiltersPerformance getFiltersPerf() { - return filtersPerf; - } - - public void setTryAdaptive(boolean tryAdaptive) { - this.tryAdaptive = tryAdaptive; - } + public void setTryAdaptive(final boolean tryAdaptive) { + this.tryAdaptive = tryAdaptive; + } } diff --git a/teavm/src/main/java/it/cavallium/warppi/gui/graphicengine/html/HtmlEngine.java b/teavm/src/main/java/it/cavallium/warppi/gui/graphicengine/html/HtmlEngine.java index f3403657..f4bc812f 100644 --- a/teavm/src/main/java/it/cavallium/warppi/gui/graphicengine/html/HtmlEngine.java +++ b/teavm/src/main/java/it/cavallium/warppi/gui/graphicengine/html/HtmlEngine.java @@ -33,9 +33,9 @@ public class HtmlEngine implements GraphicEngine { private RenderingLoop renderingLoop; private HtmlRenderer renderer; private int width, height; - private final int frameTime = (int) (1000d/10d); + private final int frameTime = (int) (1000d / 10d); private final BehaviorSubject onResize = BehaviorSubject.create(); - + @Override public int[] getSize() { return new int[] { getWidth(), getHeight() }; @@ -47,50 +47,50 @@ public class HtmlEngine implements GraphicEngine { } @Override - public void setTitle(String title) { + public void setTitle(final String title) { HtmlEngine.setHTMLTitle(title); } - @JSBody(params = {"wndTitle"}, script = "document.title = wndTitle") + @JSBody(params = { "wndTitle" }, script = "document.title = wndTitle") private static native void setHTMLTitle(String wndTitle); - - @Override - public void setResizable(boolean r) {} @Override - public void setDisplayMode(int ww, int wh) { + public void setResizable(final boolean r) {} + + @Override + public void setDisplayMode(final int ww, final int wh) { canvas.setWidth(ww); width = ww; canvas.setHeight(wh); height = wh; } - private String previousValue=""; - + private String previousValue = ""; + @Override - public void create(Runnable onInitialized) { + public void create(final Runnable onInitialized) { exitSemaphore = Engine.getPlatform().newSemaphore(0); width = -1; height = -1; - canvas = (HTMLCanvasElement) document.createElement("canvas"); - g = (CanvasRenderingContext2D ) canvas.getContext("2d"); - HTMLInputElement keyInput = (HTMLInputElement) document.createElement("input"); + canvas = (HTMLCanvasElement) HtmlEngine.document.createElement("canvas"); + g = (CanvasRenderingContext2D) canvas.getContext("2d"); + final HTMLInputElement keyInput = (HTMLInputElement) HtmlEngine.document.createElement("input"); keyInput.setType("text"); keyInput.getStyle().setProperty("opacity", "0.1"); setDisplayMode(480, 320); - document.getElementById("container").appendChild(canvas); - document.getBody().appendChild(keyInput); + HtmlEngine.document.getElementById("container").appendChild(canvas); + HtmlEngine.document.getBody().appendChild(keyInput); keyInput.setTabIndex(0); - keyInput.addEventListener("keydown", (KeyboardEvent evt) -> { + keyInput.addEventListener("keydown", (final KeyboardEvent evt) -> { evt.preventDefault(); new Thread(() -> { previousValue = keyInput.getValue(); Keyboard.debugKeyPressed(evt.getKeyCode()); System.out.println(evt.getKeyCode()); - System.out.println(""+(int) evt.getKey().charAt(0)); + System.out.println("" + (int) evt.getKey().charAt(0)); }).start(); }); - keyInput.addEventListener("input", (Event evt) -> { + keyInput.addEventListener("input", (final Event evt) -> { evt.preventDefault(); final String previousValue = this.previousValue; final String newValue = keyInput.getValue(); @@ -99,121 +99,101 @@ public class HtmlEngine implements GraphicEngine { new Thread(() -> { if (newLen == prevLen) { - - } else if (newLen - prevLen == 1) { - Keyboard.debugKeyPressed((int) newValue.toUpperCase().charAt(newLen-1)); - } else if (newLen - prevLen > 1) { - for (int i = 0; i < newLen - prevLen; i++) { - Keyboard.debugKeyPressed((int) newValue.toUpperCase().charAt(prevLen + i)); - } - } else if (newLen - prevLen < 1) { - for (int i = 0; i < prevLen - newLen; i++) { + + } else if (newLen - prevLen == 1) + Keyboard.debugKeyPressed(newValue.toUpperCase().charAt(newLen - 1)); + else if (newLen - prevLen > 1) + for (int i = 0; i < newLen - prevLen; i++) + Keyboard.debugKeyPressed(newValue.toUpperCase().charAt(prevLen + i)); + else if (newLen - prevLen < 1) + for (int i = 0; i < prevLen - newLen; i++) Keyboard.debugKeyPressed(8); - } - } }).start(); }); - canvas.addEventListener("click", (Event evt) -> { + canvas.addEventListener("click", (final Event evt) -> { keyInput.focus(); }); - document.addEventListener("DOMContentLoaded", (Event e) -> { + HtmlEngine.document.addEventListener("DOMContentLoaded", (final Event e) -> { keyInput.focus(); }); - NodeList buttons = document.getBody().getElementsByTagName("button"); - for (int i = 0; i < buttons.getLength(); i++) { - if (buttons.item(i).hasAttribute("keycode")) { - buttons.item(i).addEventListener("click", (Event evt) -> { + final NodeList buttons = HtmlEngine.document.getBody().getElementsByTagName("button"); + for (int i = 0; i < buttons.getLength(); i++) + if (buttons.item(i).hasAttribute("keycode")) + buttons.item(i).addEventListener("click", (final Event evt) -> { evt.preventDefault(); - EventTarget target = evt.getCurrentTarget(); - HTMLButtonElement button = target.cast(); + final EventTarget target = evt.getCurrentTarget(); + final HTMLButtonElement button = target.cast(); new Thread(() -> { try { if (button.hasAttribute("keycode") && button.getAttribute("keycode").contains(",")) { - String code = button.getAttribute("keycode"); - String[] coordinates = code.split(",", 2); - boolean removeshift = Keyboard.shift && Integer.parseInt(coordinates[0]) != 0 && Integer.parseInt(coordinates[1]) != 0; - boolean removealpha = Keyboard.alpha && Integer.parseInt(coordinates[0]) != 0 && Integer.parseInt(coordinates[1]) != 1; + final String code = button.getAttribute("keycode"); + final String[] coordinates = code.split(",", 2); + final boolean removeshift = Keyboard.shift && Integer.parseInt(coordinates[0]) != 0 && Integer.parseInt(coordinates[1]) != 0; + final boolean removealpha = Keyboard.alpha && Integer.parseInt(coordinates[0]) != 0 && Integer.parseInt(coordinates[1]) != 1; Keyboard.keyPressedRaw(Integer.parseInt(coordinates[0]), Integer.parseInt(coordinates[1])); - if (removeshift) { - Keyboard.keyPressedRaw(0,0); - } - if (removealpha) { - Keyboard.keyPressedRaw(0,1); - } + if (removeshift) + Keyboard.keyPressedRaw(0, 0); + if (removealpha) + Keyboard.keyPressedRaw(0, 1); Thread.sleep(100); Keyboard.keyReleasedRaw(Integer.parseInt(coordinates[0]), Integer.parseInt(coordinates[1])); - if (removeshift) { - Keyboard.keyReleasedRaw(0,0); - } - if (removealpha) { - Keyboard.keyReleasedRaw(0,1); - } - } else { - if (Keyboard.alpha && !Keyboard.shift) { - if (button.hasAttribute("keycodea")) { - Keyboard.debugKeyPressed(Integer.parseInt(button.getAttribute("keycodea"))); - } else { - Keyboard.debugKeyPressed(Integer.parseInt(button.getAttribute("keycode"))); - } - } else if (!Keyboard.alpha && Keyboard.shift) { - if (button.hasAttribute("keycodes")) { - Keyboard.debugKeyPressed(Integer.parseInt(button.getAttribute("keycodes"))); - } else { - Keyboard.debugKeyPressed(Integer.parseInt(button.getAttribute("keycode"))); - } - } else if (Keyboard.alpha && Keyboard.shift) { - if (button.hasAttribute("keycodesa")) { - Keyboard.debugKeyPressed(Integer.parseInt(button.getAttribute("keycodesa"))); - } else { - if (button.hasAttribute("keycodes")) { - Keyboard.debugKeyPressed(Integer.parseInt(button.getAttribute("keycodes"))); - } else { - Keyboard.debugKeyPressed(Integer.parseInt(button.getAttribute("keycode"))); - } - } - } else { + if (removeshift) + Keyboard.keyReleasedRaw(0, 0); + if (removealpha) + Keyboard.keyReleasedRaw(0, 1); + } else if (Keyboard.alpha && !Keyboard.shift) { + if (button.hasAttribute("keycodea")) + Keyboard.debugKeyPressed(Integer.parseInt(button.getAttribute("keycodea"))); + else Keyboard.debugKeyPressed(Integer.parseInt(button.getAttribute("keycode"))); - } - } - } catch (Exception ex) { + } else if (!Keyboard.alpha && Keyboard.shift) { + if (button.hasAttribute("keycodes")) + Keyboard.debugKeyPressed(Integer.parseInt(button.getAttribute("keycodes"))); + else + Keyboard.debugKeyPressed(Integer.parseInt(button.getAttribute("keycode"))); + } else if (Keyboard.alpha && Keyboard.shift) { + if (button.hasAttribute("keycodesa")) + Keyboard.debugKeyPressed(Integer.parseInt(button.getAttribute("keycodesa"))); + else if (button.hasAttribute("keycodes")) + Keyboard.debugKeyPressed(Integer.parseInt(button.getAttribute("keycodes"))); + else + Keyboard.debugKeyPressed(Integer.parseInt(button.getAttribute("keycode"))); + } else + Keyboard.debugKeyPressed(Integer.parseInt(button.getAttribute("keycode"))); + } catch (final Exception ex) { ex.printStackTrace(); } }).start(); }); - } - } renderer = new HtmlRenderer(this, g); initialized = true; - if (onInitialized != null) { + if (onInitialized != null) onInitialized.run(); - } } @Override public int getWidth() { - if (width == -1) { + if (width == -1) width = canvas.getWidth(); - } return width; } @Override public int getHeight() { - if (height == -1) { + if (height == -1) height = canvas.getHeight(); - } return height; } @Override public void destroy() { - document.getBody().removeChild(canvas); + HtmlEngine.document.getBody().removeChild(canvas); initialized = false; exitSemaphore.release(); } @Override - public void start(RenderingLoop d) { + public void start(final RenderingLoop d) { renderingLoop = d; final Thread th = new Thread(() -> { try { @@ -228,9 +208,8 @@ public class HtmlEngine implements GraphicEngine { if (extraTimeInt + deltaInt < frameTime) { Thread.sleep(frameTime - (extraTimeInt + deltaInt)); extratime = 0; - } else { + } else extratime += delta - frameTime; - } } } catch (final InterruptedException e) { e.printStackTrace(); @@ -252,17 +231,17 @@ public class HtmlEngine implements GraphicEngine { } @Override - public HtmlFont loadFont(String fontName) throws IOException { + public HtmlFont loadFont(final String fontName) throws IOException { return new HtmlFont(fontName); } @Override - public HtmlFont loadFont(String path, String fontName) throws IOException { + public HtmlFont loadFont(final String path, final String fontName) throws IOException { return new HtmlFont(fontName); } @Override - public HtmlSkin loadSkin(String file) throws IOException { + public HtmlSkin loadSkin(final String file) throws IOException { return new HtmlSkin(file); } diff --git a/teavm/src/main/java/it/cavallium/warppi/gui/graphicengine/html/HtmlFont.java b/teavm/src/main/java/it/cavallium/warppi/gui/graphicengine/html/HtmlFont.java index 5d89c35d..b66f448d 100644 --- a/teavm/src/main/java/it/cavallium/warppi/gui/graphicengine/html/HtmlFont.java +++ b/teavm/src/main/java/it/cavallium/warppi/gui/graphicengine/html/HtmlFont.java @@ -14,50 +14,42 @@ public class HtmlFont extends RFTFont { public HTMLCanvasElement imgEl; public CanvasRenderingContext2D imgElCtx; - - public HtmlFont(String fontName) throws IOException { + + public HtmlFont(final String fontName) throws IOException { super(fontName); - HTMLDocument doc = Window.current().getDocument(); + final HTMLDocument doc = Window.current().getDocument(); imgEl = doc.createElement("canvas").cast(); imgEl.setClassName("hidden"); doc.getBody().appendChild(imgEl); imgElCtx = imgEl.getContext("2d").cast(); - imgEl.setWidth(this.charW); - imgEl.setHeight(this.charH * intervalsTotalSize); - - int screenPos = 0; + imgEl.setWidth(charW); + imgEl.setHeight(charH * intervalsTotalSize); int currentInt; int currentIntBitPosition; int bitData; - int j; imgElCtx.clearRect(0, 0, imgEl.getWidth(), imgEl.getHeight()); imgElCtx.setFillStyle("#000"); - int minBound = 0, maxBound = intervalsTotalSize-1; - for (int charIndex = minBound; charIndex < maxBound; charIndex++) { - for (int dy = 0; dy < charH; dy++) { + final int minBound = 0, maxBound = intervalsTotalSize - 1; + for (int charIndex = minBound; charIndex < maxBound; charIndex++) + for (int dy = 0; dy < charH; dy++) for (int dx = 0; dx < charW; dx++) { - j = dx; final int bit = dx + dy * charW; - currentInt = (int) (Math.floor(bit) / (HtmlFont.intBits)); - currentIntBitPosition = bit - (currentInt * HtmlFont.intBits); + currentInt = (int) (Math.floor(bit) / RFTFont.intBits); + currentIntBitPosition = bit - currentInt * RFTFont.intBits; final int charIdx = charIndex * charIntCount + currentInt; if (charIdx >= 0 && charIdx < chars32.length) { - bitData = (chars32[charIdx] >> currentIntBitPosition) & 1; - if (bitData == 1) { - imgElCtx.fillRect( dx, charIndex*charH+dy, 1, 1 ); - } + bitData = chars32[charIdx] >> currentIntBitPosition & 1; + if (bitData == 1) + imgElCtx.fillRect(dx, charIndex * charH + dy, 1, 1); } } - } - } } - + @Override - public void use(GraphicEngine d) { - if (d.getRenderer() instanceof HtmlRenderer) { + public void use(final GraphicEngine d) { + if (d.getRenderer() instanceof HtmlRenderer) ((HtmlRenderer) d.getRenderer()).f = this; - } } } \ No newline at end of file diff --git a/teavm/src/main/java/it/cavallium/warppi/gui/graphicengine/html/HtmlRenderer.java b/teavm/src/main/java/it/cavallium/warppi/gui/graphicengine/html/HtmlRenderer.java index fba87b3e..b65610e6 100644 --- a/teavm/src/main/java/it/cavallium/warppi/gui/graphicengine/html/HtmlRenderer.java +++ b/teavm/src/main/java/it/cavallium/warppi/gui/graphicengine/html/HtmlRenderer.java @@ -6,95 +6,67 @@ import it.cavallium.warppi.StaticVars; import it.cavallium.warppi.gui.graphicengine.Renderer; public class HtmlRenderer implements Renderer { - private static final boolean ENABLE_SUPERSAMPLING = false; - private static final boolean ENABLE_TRANSPARENCY = true; private String currentColor = "#000000ff"; private String clearColor = "#000000ff"; HtmlFont f = null; HtmlSkin currentSkin = null; private final CanvasRenderingContext2D g; private final HtmlEngine e; - public HtmlRenderer(HtmlEngine e, CanvasRenderingContext2D g) { + + public HtmlRenderer(final HtmlEngine e, final CanvasRenderingContext2D g) { this.g = g; this.e = e; } - private String toHex(int c) { - final int a = c >> 24 & 0xFF; - final int r = c >> 16 & 0xFF; - final int gg = c >> 8 & 0xFF; - final int b = c & 0xFF; - return String.format("#%02x%02x%02x%02x", r, gg, b, a); + private String toHex(final int r, final int g, final int b) { + return String.format("#%02x%02x%02x", r, g, b); } - private String toHex8(int c) { - final int r = c >> 16 & 0xFF; - final int gg = c >> 8 & 0xFF; - final int b = c & 0xFF; - return String.format("#%02x%02x%02x", r, gg, b); + private String toHex(final int r, final int g, final int b, final int a) { + return String.format("#%02x%02x%02x%02x", r, g, b, a); } - private String toHex(int r, int g, int b) { - return String.format("#%02x%02x%02x", r, g, b); - } - - private String toHex(int r, int g, int b, int a) { - return String.format("#%02x%02x%02x%02x", r, g, b, a); - } - @Override public int glGetClearColor() { return hexToInt(clearColor); } - private int hexToInt(String hex) { - switch (hex.length()) { - case 6: - return (0xFF << 24) | - (Integer.valueOf(hex.substring(0, 2), 16) << 16) | - (Integer.valueOf(hex.substring(2, 4), 16) << 8) | - Integer.valueOf(hex.substring(4, 6), 16); - case 6+1: - return (0xFF << 24) | - (Integer.valueOf(hex.substring(0+1, 2+1), 16) << 16) | - (Integer.valueOf(hex.substring(2+1, 4+1), 16) << 8) | - Integer.valueOf(hex.substring(4+1, 6+1), 16); - case 8: - return (Integer.valueOf(hex.substring(6, 8), 16) << 24) | - (Integer.valueOf(hex.substring(0, 2), 16) << 16) | - (Integer.valueOf(hex.substring(2, 4), 16) << 8) | - Integer.valueOf(hex.substring(4, 6), 16); - case 8+1: - return (Integer.valueOf(hex.substring(6+1, 8+1), 16) << 24) | - (Integer.valueOf(hex.substring(0+1, 2+1), 16) << 16) | - (Integer.valueOf(hex.substring(2+1, 4+1), 16) << 8) | - Integer.valueOf(hex.substring(4+1, 6+1), 16); - } - return 0xFF000000; + private int hexToInt(final String hex) { + switch (hex.length()) { + case 6: + return 0xFF << 24 | Integer.valueOf(hex.substring(0, 2), 16) << 16 | Integer.valueOf(hex.substring(2, 4), 16) << 8 | Integer.valueOf(hex.substring(4, 6), 16); + case 6 + 1: + return 0xFF << 24 | Integer.valueOf(hex.substring(0 + 1, 2 + 1), 16) << 16 | Integer.valueOf(hex.substring(2 + 1, 4 + 1), 16) << 8 | Integer.valueOf(hex.substring(4 + 1, 6 + 1), 16); + case 8: + return Integer.valueOf(hex.substring(6, 8), 16) << 24 | Integer.valueOf(hex.substring(0, 2), 16) << 16 | Integer.valueOf(hex.substring(2, 4), 16) << 8 | Integer.valueOf(hex.substring(4, 6), 16); + case 8 + 1: + return Integer.valueOf(hex.substring(6 + 1, 8 + 1), 16) << 24 | Integer.valueOf(hex.substring(0 + 1, 2 + 1), 16) << 16 | Integer.valueOf(hex.substring(2 + 1, 4 + 1), 16) << 8 | Integer.valueOf(hex.substring(4 + 1, 6 + 1), 16); + } + return 0xFF000000; } @Override - public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth, - float uvHeight) { - if (currentSkin != null) { + public void glFillRect(final float x, final float y, final float width, final float height, final float uvX, + final float uvY, final float uvWidth, final float uvHeight) { + if (currentSkin != null) glDrawSkin((int) x, (int) y, (int) (x + width), (int) (y + height), (int) uvX, (int) uvY, (int) (uvWidth + uvX), (int) (uvHeight + uvY), true); - } else { + else glFillColor(x, y, width, height); - } } - + @SuppressWarnings("unused") - private void glDrawSkin(int x0, int y0, int x1, int y1, int s0, int t0, int s1, int t1, boolean transparent) { + private void glDrawSkin(int x0, int y0, final int x1, final int y1, int s0, int t0, int s1, int t1, + final boolean transparent) { final int[] size = e.getSize(); - + x0 += StaticVars.screenPos[0]; y0 += StaticVars.screenPos[1]; final double incrementX = Math.abs((double) (x1 - x0) / (double) (s1 - s0)); final double incrementY = Math.abs((double) (y1 - y0) / (double) (t1 - t0)); final boolean flippedX = (x1 - x0) / (s1 - s0) < 0; final boolean flippedY = (y1 - y0) / (t1 - t0) < 0; - int oldColor = 0; - int newColor; + final int oldColor = 0; + final int newColor; final int onex = s0 <= s1 ? 1 : -1; final int oney = t0 <= t1 ? 1 : -1; int width = 0; @@ -111,138 +83,116 @@ public class HtmlRenderer implements Renderer { t1 = t00; height = t1 - t0; } - if (x0 >= size[0] || y0 >= size[0]) { + if (x0 >= size[0] || y0 >= size[0]) return; - } - if (x0 + width >= size[0]) { + if (x0 + width >= size[0]) s1 = size[0] - x0 + s0; - } - if (y0 + height >= size[1]) { + if (y0 + height >= size[1]) t1 = size[1] - y0 + t0; - } if (x0 < 0) { if (onex == -1) { width += x0; s1 += x0 + 1; - } else { + } else s0 -= x0; - } x0 = 0; } if (y0 < 0) { if (oney == -1) { height += y0; t1 += y0 + 1; - } else { + } else t0 -= y0; - } y0 = 0; } - g.drawImage(currentSkin.getImgElement(), s0, t0, s1-s0, t1-t0, x0, y0, x1-x0, y1-y0); + g.drawImage(currentSkin.getImgElement(), s0, t0, s1 - s0, t1 - t0, x0, y0, x1 - x0, y1 - y0); } @Override - public void glFillColor(float x, float y, float width, float height) { + public void glFillColor(float x, float y, final float width, final float height) { x += StaticVars.screenPos[0]; y += StaticVars.screenPos[1]; g.setFillStyle(currentColor); - g.fillRect( x, y, width, height ); + g.fillRect(x, y, width, height); } @Override - public void glDrawStringRight(float x, float y, String text) { + public void glDrawStringRight(final float x, final float y, final String text) { glDrawStringLeft(x - f.getStringWidth(text), y, text); } @Override - public void glDrawStringLeft(float x, float y, String textString) { + public void glDrawStringLeft(float x, float y, final String textString) { x += StaticVars.screenPos[0]; y += StaticVars.screenPos[1]; - + f.imgElCtx.setGlobalCompositeOperation("source-in"); f.imgElCtx.setFillStyle(currentColor); f.imgElCtx.fillRect(0, 0, f.imgEl.getWidth(), f.imgEl.getHeight()); final int[] text = f.getCharIndexes(textString); - final int[] screenSize = e.getSize(); int cpos; final int l = text.length; for (int i = 0; i < l; i++) { - cpos = (i * (f.charW)); + cpos = i * f.charW; final int charIndex = text[i]; - g.drawImage(f.imgEl, 0, charIndex*f.charH, f.charW, f.charH, x+cpos, y, f.charW, f.charH); + g.drawImage(f.imgEl, 0, charIndex * f.charH, f.charW, f.charH, x + cpos, y, f.charW, f.charH); } } - - private int stackColors(int... color) { - double a = 0; - double r = 0; - double g = 0; - double b = 0; - for (final int newColor : color) { - final double alpha = (newColor >> 24 & 0xFF) / 255d; - a = a * (1d - alpha) + (newColor >> 24 & 0xFF) * alpha; - r = r * (1d - alpha) + (newColor >> 16 & 0xFF) * alpha; - g = g * (1d - alpha) + (newColor >> 8 & 0xFF) * alpha; - b = b * (1d - alpha) + (newColor & 0xFF) * alpha; - } - return ((int) a) << 24 | ((int) r) << 16 | ((int) g) << 8 | ((int) b); - } @Override - public void glDrawStringCenter(float x, float y, String text) { - glDrawStringLeft(x - (f.getStringWidth(text) / 2), y, text); + public void glDrawStringCenter(final float x, final float y, final String text) { + glDrawStringLeft(x - f.getStringWidth(text) / 2, y, text); } @Override - public void glDrawLine(float x0, float y0, float x1, float y1) { - if (x1-x0 > 0 && y1-y0 > 0) { + public void glDrawLine(final float x0, final float y0, final float x1, final float y1) { + if (x1 - x0 > 0 && y1 - y0 > 0) { g.beginPath(); g.moveTo(x0, y0); g.lineTo(x1, y1); g.stroke(); - } else { - g.fillRect(x0, y0, (x1-x0)+1, (y1-y0)+1); - } + } else + g.fillRect(x0, y0, x1 - x0 + 1, y1 - y0 + 1); } @Override - public void glDrawCharRight(int x, int y, char ch) { + public void glDrawCharRight(final int x, final int y, final char ch) { glDrawStringRight(x, y, ch + ""); } @Override - public void glDrawCharLeft(int x, int y, char ch) { + public void glDrawCharLeft(final int x, final int y, final char ch) { glDrawStringLeft(x, y, ch + ""); } @Override - public void glDrawCharCenter(int x, int y, char ch) { + public void glDrawCharCenter(final int x, final int y, final char ch) { glDrawStringCenter(x, y, ch + ""); } @Override - public void glColor4i(int red, int green, int blue, int alpha) { + public void glColor4i(final int red, final int green, final int blue, final int alpha) { g.setFillStyle(currentColor = toHex(red, green, blue, alpha)); } @Override - public void glColor4f(float red, float green, float blue, float alpha) { + public void glColor4f(final float red, final float green, final float blue, final float alpha) { glColor4i((int) (red * 255d), (int) (green * 255d), (int) (blue * 255d), (int) (alpha * 255d)); } @Override - public void glColor3i(int r, int gg, int b) { + public void glColor3i(final int r, final int gg, final int b) { g.setFillStyle(currentColor = toHex(r, gg, b)); } @Override - public void glColor3f(float red, float green, float blue) { + public void glColor3f(final float red, final float green, final float blue) { glColor3i((int) (red * 255d), (int) (green * 255d), (int) (blue * 255d)); } @Override - public void glColor(int c) { + public void glColor(final int c) { final int a = c >> 24 & 0xFF; final int r = c >> 16 & 0xFF; final int gg = c >> 8 & 0xFF; @@ -256,20 +206,17 @@ public class HtmlRenderer implements Renderer { } @Override - public void glClearColor4i(int red, int green, int blue, int alpha) { + public void glClearColor4i(final int red, final int green, final int blue, final int alpha) { clearColor = toHex(red, green, blue, alpha); } @Override - public void glClearColor4f(float red, float green, float blue, float alpha) { - clearColor = toHex((int)(red*255), - (int)(green*255), - (int)(blue*255), - (int)(alpha*255)); + public void glClearColor4f(final float red, final float green, final float blue, final float alpha) { + clearColor = toHex((int) (red * 255), (int) (green * 255), (int) (blue * 255), (int) (alpha * 255)); } @Override - public void glClearColor(int c) { + public void glClearColor(final int c) { final int r = c >> 16 & 0xFF; final int gg = c >> 8 & 0xFF; final int b = c & 0xFF; @@ -277,7 +224,7 @@ public class HtmlRenderer implements Renderer { } @Override - public void glClear(int screenWidth, int screenHeight) { + public void glClear(final int screenWidth, final int screenHeight) { g.setFillStyle(clearColor); g.fillRect(0, 0, screenWidth, screenHeight); g.setFillStyle(currentColor); diff --git a/teavm/src/main/java/it/cavallium/warppi/gui/graphicengine/html/HtmlSkin.java b/teavm/src/main/java/it/cavallium/warppi/gui/graphicengine/html/HtmlSkin.java index 9e006c3f..1a54a470 100644 --- a/teavm/src/main/java/it/cavallium/warppi/gui/graphicengine/html/HtmlSkin.java +++ b/teavm/src/main/java/it/cavallium/warppi/gui/graphicengine/html/HtmlSkin.java @@ -23,11 +23,12 @@ public class HtmlSkin implements Skin { private HTMLImageElement imgEl; - public HtmlSkin(String file) throws IOException { + public HtmlSkin(final String file) throws IOException { load(file); } - public void use(GraphicEngine d) { + @Override + public void use(final GraphicEngine d) { if (d instanceof HtmlEngine) { if (!initd) initialize(d); @@ -37,24 +38,24 @@ public class HtmlSkin implements Skin { @Override public void load(String file) throws IOException { - if (!file.startsWith("/")) - file = "/"+file; - url = Engine.getPlatform().getStorageUtils().getBasePath()+file; + if (!file.startsWith("/")) + file = "/" + file; + url = Engine.getPlatform().getStorageUtils().getBasePath() + file; try { - InputStream stream = Engine.getPlatform().getStorageUtils().getResourceStream(file); - PngReader r = new PngReader(stream); + final InputStream stream = Engine.getPlatform().getStorageUtils().getResourceStream(file); + final PngReader r = new PngReader(stream); skinSize = new int[] { r.imgInfo.cols, r.imgInfo.rows }; r.close(); - } catch (URISyntaxException e) { - IOException ex = new IOException(); + } catch (final URISyntaxException e) { + final IOException ex = new IOException(); ex.initCause(e); throw ex; } } @Override - public void initialize(GraphicEngine d) { - HTMLDocument doc = Window.current().getDocument(); + public void initialize(final GraphicEngine d) { + final HTMLDocument doc = Window.current().getDocument(); imgEl = doc.createElement("img").cast(); imgEl.setSrc(url); imgEl.setClassName("hidden"); @@ -76,11 +77,11 @@ public class HtmlSkin implements Skin { public int getSkinHeight() { return skinSize[1]; } - + public final String getUrl() { return url; - } - + } + public final HTMLImageElement getImgElement() { return imgEl; } diff --git a/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMBoot.java b/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMBoot.java index c45cb4a2..a3befe43 100644 --- a/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMBoot.java +++ b/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMBoot.java @@ -4,7 +4,7 @@ import it.cavallium.warppi.boot.Boot; public class TeaVMBoot { - public static void main(String[] args) throws Exception { + public static void main(final String[] args) throws Exception { Boot.boot(new TeaVMPlatform(), args); } diff --git a/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMConsoleUtils.java b/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMConsoleUtils.java index d2f5f0d6..a7412ddb 100644 --- a/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMConsoleUtils.java +++ b/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMConsoleUtils.java @@ -11,74 +11,74 @@ public class TeaVMConsoleUtils implements it.cavallium.warppi.Platform.ConsoleUt public TeaVMConsoleUtils() { os = new AdvancedOutputStream() { - private void print(PrintStream stream, String str) { + private void print(final PrintStream stream, final String str) { stream.print(fixString(str)); } - private void println(PrintStream stream, String str) { + private void println(final PrintStream stream, final String str) { stream.println(fixString(str)); } - private void println(PrintStream stream) { + private void println(final PrintStream stream) { stream.println(); } - private String fixString(String str) { + private String fixString(final String str) { return str.replace("" + MathematicalSymbols.NTH_ROOT, "root").replace("" + MathematicalSymbols.SQUARE_ROOT, "sqrt").replace("" + MathematicalSymbols.POWER, "powerOf").replace("" + MathematicalSymbols.POWER_OF_TWO, "powerOfTwo").replace("" + MathematicalSymbols.SINE, "sine").replace("" + MathematicalSymbols.COSINE, "cosine").replace("" + MathematicalSymbols.TANGENT, "tangent").replace("" + MathematicalSymbols.ARC_SINE, "asin").replace("" + MathematicalSymbols.ARC_COSINE, "acos").replace("" + MathematicalSymbols.ARC_TANGENT, "atan").replace("" + MathematicalSymbols.UNDEFINED, "undefined").replace("" + MathematicalSymbols.PI, "PI").replace("" + MathematicalSymbols.EULER_NUMBER, "EULER_NUMBER").replace("" + MathematicalSymbols.X, "X").replace("" + MathematicalSymbols.Y, "Y"); } - public void println(Object str) { + @Override + public void println(final Object str) { println(0, str); } - public void println(int level) { - if (StaticVars.outputLevel >= level) { - if (StaticVars.outputLevel == 0) { + @Override + public void println(final int level) { + if (StaticVars.outputLevel >= level) + if (StaticVars.outputLevel == 0) println(System.out); - } else { + else println(System.out); - } - } } - public void println(int level, Object str) { + @Override + public void println(final int level, final Object str) { if (StaticVars.outputLevel >= level) { final String time = getTimeString(); - if (StaticVars.outputLevel == 0) { + if (StaticVars.outputLevel == 0) println(System.out, "[" + time + "] " + str); - } else { + else println(System.out, "[" + time + "] " + str); - } } } - public void print(int level, String str) { - if (StaticVars.outputLevel >= level) { - if (StaticVars.outputLevel == 0) { + @Override + public void print(final int level, final String str) { + if (StaticVars.outputLevel >= level) + if (StaticVars.outputLevel == 0) print(System.out, str); - } else { + else print(System.out, str); - } - } } - public void println(int level, String prefix, String str) { + @Override + public void println(final int level, final String prefix, final String str) { if (StaticVars.outputLevel >= level) { final String time = getTimeString(); - if (StaticVars.outputLevel == 0) { + if (StaticVars.outputLevel == 0) println(System.out, "[" + time + "][" + prefix + "] " + str); - } else { + else println(System.out, "[" + time + "][" + prefix + "] " + str); - } } } - public void println(int level, String... parts) { + @Override + public void println(final int level, final String... parts) { if (StaticVars.outputLevel >= level) { final String time = getTimeString(); - StringBuilder output = new StringBuilder(); - for (int i = 0; i < parts.length; i++) { + final StringBuilder output = new StringBuilder(); + for (int i = 0; i < parts.length; i++) if (i + 1 == parts.length) { output.append(' '); output.append(parts[i]); @@ -87,24 +87,22 @@ public class TeaVMConsoleUtils implements it.cavallium.warppi.Platform.ConsoleUt output.append(parts[i]); output.append(']'); } - } output.insert(0, '['); output.insert(1, time); output.insert(time.length() + 1, ']'); - if (StaticVars.outputLevel == 0) { + if (StaticVars.outputLevel == 0) println(System.out, output.toString()); - } else { + else println(System.out, output.toString()); - } } } private String getTimeString() { - return System.currentTimeMillis()+""; + return System.currentTimeMillis() + ""; } }; } - + @Override public AdvancedOutputStream out() { return os; diff --git a/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMGpio.java b/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMGpio.java index 181e05b1..b293cd06 100644 --- a/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMGpio.java +++ b/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMGpio.java @@ -33,35 +33,33 @@ public class TeaVMGpio implements it.cavallium.warppi.Platform.Gpio { } @Override - public void wiringPiSetupPhys() { - } + public void wiringPiSetupPhys() {} @Override - public void pinMode(int i, int type) { - } + public void pinMode(final int i, final int type) {} @Override - public void digitalWrite(int pin, int val) { + public void digitalWrite(final int pin, final int val) { throw new java.lang.UnsupportedOperationException("Not implemented."); } @Override - public void digitalWrite(int pin, boolean val) { + public void digitalWrite(final int pin, final boolean val) { throw new java.lang.UnsupportedOperationException("Not implemented."); } @Override - public void pwmWrite(int pin, int val) { + public void pwmWrite(final int pin, final int val) { throw new java.lang.UnsupportedOperationException("Not implemented."); } - + @Override - public void delayMicroseconds(int t) { + public void delayMicroseconds(final int t) { throw new java.lang.UnsupportedOperationException("Not implemented."); } - + @Override - public int digitalRead(int pin) { + public int digitalRead(final int pin) { throw new java.lang.UnsupportedOperationException("Not implemented."); } diff --git a/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMPlatform.java b/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMPlatform.java index 9dc28faa..a053be53 100644 --- a/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMPlatform.java +++ b/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMPlatform.java @@ -34,7 +34,7 @@ public class TeaVMPlatform implements Platform { el.put("HTML5 engine", new HtmlEngine()); settings = new TeaVMSettings(); } - + @Override public ConsoleUtils getConsoleUtils() { return cu; @@ -61,25 +61,22 @@ public class TeaVMPlatform implements Platform { } @Override - public void setThreadName(Thread t, String name) { - } + public void setThreadName(final Thread t, final String name) {} @Override - public void setThreadDaemon(Thread t) { - } + public void setThreadDaemon(final Thread t) {} @Override - public void setThreadDaemon(Thread t, boolean value) { - } + public void setThreadDaemon(final Thread t, final boolean value) {} @Override - public void exit(int value) { + public void exit(final int value) { System.err.println("====================PROGRAM END===================="); } @Override public void gc() { - + } @Override @@ -91,21 +88,21 @@ public class TeaVMPlatform implements Platform { public String getOsName() { return on; } - + private boolean shift, alpha; - + @Override - public void alphaChanged(boolean alpha) { + public void alphaChanged(final boolean alpha) { this.alpha = alpha; - HTMLDocument doc = Window.current().getDocument(); - doc.getBody().setClassName((shift ? "shift " : "") + (alpha ? "alpha": "")); + final HTMLDocument doc = Window.current().getDocument(); + doc.getBody().setClassName((shift ? "shift " : "") + (alpha ? "alpha" : "")); } @Override - public void shiftChanged(boolean shift) { + public void shiftChanged(final boolean shift) { this.shift = shift; - HTMLDocument doc = Window.current().getDocument(); - doc.getBody().setClassName((shift ? "shift " : "") + (alpha ? "alpha": "")); + final HTMLDocument doc = Window.current().getDocument(); + doc.getBody().setClassName((shift ? "shift " : "") + (alpha ? "alpha" : "")); } @Override @@ -114,12 +111,12 @@ public class TeaVMPlatform implements Platform { } @Override - public Semaphore newSemaphore(int i) { + public Semaphore newSemaphore(final int i) { return new TeaVMSemaphore(i); } @Override - public URLClassLoader newURLClassLoader(URL[] urls) { + public URLClassLoader newURLClassLoader(final URL[] urls) { return new TeaVMURLClassLoader(urls); } @@ -129,17 +126,17 @@ public class TeaVMPlatform implements Platform { } @Override - public GraphicEngine getEngine(String string) throws NullPointerException { + public GraphicEngine getEngine(final String string) throws NullPointerException { return el.get(string); } @Override - public void throwNewExceptionInInitializerError(String text) { + public void throwNewExceptionInInitializerError(final String text) { throw new NullPointerException(); } @Override - public String[] stacktraceToString(Error e) { + public String[] stacktraceToString(final Error e) { return e.getMessage().toUpperCase().replace("\r", "").split("\n"); } @@ -197,17 +194,17 @@ public class TeaVMPlatform implements Platform { } @Override - public void zip(String targetPath, String destinationFilePath, String password) { + public void zip(final String targetPath, final String destinationFilePath, final String password) { throw new java.lang.UnsupportedOperationException("Not implemented."); } @Override - public void unzip(String targetZipFilePath, String destinationFolderPath, String password) { + public void unzip(final String targetZipFilePath, final String destinationFolderPath, final String password) { throw new java.lang.UnsupportedOperationException("Not implemented."); } @Override - public boolean compile(String[] command, PrintWriter printWriter, PrintWriter errors) { + public boolean compile(final String[] command, final PrintWriter printWriter, final PrintWriter errors) { throw new java.lang.UnsupportedOperationException("Not implemented."); } diff --git a/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMPngReader.java b/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMPngReader.java index e197e7a1..2c21fce7 100644 --- a/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMPngReader.java +++ b/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMPngReader.java @@ -7,9 +7,9 @@ import it.cavallium.warppi.Platform.PngUtils.PngReader; public class TeaVMPngReader implements PngReader { - private ar.com.hjg.pngj.PngReader r; - - public TeaVMPngReader(InputStream resourceStream) { + private final ar.com.hjg.pngj.PngReader r; + + public TeaVMPngReader(final InputStream resourceStream) { r = new ar.com.hjg.pngj.PngReader(resourceStream); } @@ -23,25 +23,24 @@ public class TeaVMPngReader implements PngReader { ImageLineInt lint; while (r.hasMoreRows()) { lint = (ImageLineInt) r.readRow(); - int[] scanLine = lint.getScanline(); + final int[] scanLine = lint.getScanline(); for (int i = 0; i < width; i++) { - int offset = i * channels; + final int offset = i * channels; // Adjust the following code depending on your source image. // I need the to set the alpha channel to 0xFF000000 since my destination image // is TRANSLUCENT : BufferedImage bi = CONFIG.createCompatibleImage( width, height, Transparency.TRANSLUCENT ); // my source was 3 channels RGB without transparency int nextPixel; - if (channels == 4) { - nextPixel = (scanLine[offset] << 16) | (scanLine[offset + 1] << 8) | (scanLine[offset + 2]) | (scanLine[offset + 3] << 24); - } else if (channels == 3) { - nextPixel = (scanLine[offset] << 16) | (scanLine[offset + 1] << 8) | (scanLine[offset + 2]) | (0xFF << 24); - } else if (channels == 2) { - nextPixel = (scanLine[offset] << 16) | (scanLine[offset + 1] << 8) | 0xFF | (0xFF << 24); - } else { - nextPixel = (scanLine[offset] << 16) | (scanLine[offset] << 8) | scanLine[offset] | (0xFF << 24); - } + if (channels == 4) + nextPixel = scanLine[offset] << 16 | scanLine[offset + 1] << 8 | scanLine[offset + 2] | scanLine[offset + 3] << 24; + else if (channels == 3) + nextPixel = scanLine[offset] << 16 | scanLine[offset + 1] << 8 | scanLine[offset + 2] | 0xFF << 24; + else if (channels == 2) + nextPixel = scanLine[offset] << 16 | scanLine[offset + 1] << 8 | 0xFF | 0xFF << 24; + else + nextPixel = scanLine[offset] << 16 | scanLine[offset] << 8 | scanLine[offset] | 0xFF << 24; // I'm placing the pixels on a memory mapped file pixels[pi] = nextPixel; @@ -55,7 +54,7 @@ public class TeaVMPngReader implements PngReader { @Override public int[] getSize() { - return new int[] {r.imgInfo.cols, r.imgInfo.rows}; + return new int[] { r.imgInfo.cols, r.imgInfo.rows }; } } diff --git a/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMPngUtils.java b/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMPngUtils.java index 533bc1fc..6378dc2d 100644 --- a/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMPngUtils.java +++ b/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMPngUtils.java @@ -7,7 +7,7 @@ import it.cavallium.warppi.Platform.PngUtils; public class TeaVMPngUtils implements PngUtils { @Override - public PngReader load(InputStream resourceStream) { + public PngReader load(final InputStream resourceStream) { return new TeaVMPngReader(resourceStream); } diff --git a/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMSemaphore.java b/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMSemaphore.java index 0806cf87..ae8f3327 100644 --- a/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMSemaphore.java +++ b/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMSemaphore.java @@ -5,34 +5,32 @@ import java.util.Queue; public class TeaVMSemaphore implements it.cavallium.warppi.Platform.Semaphore { - private Queue q; - + private final Queue q; + private int freePermits = 0; - - public TeaVMSemaphore(int i) { - q = new LinkedList(); + + public TeaVMSemaphore(final int i) { + q = new LinkedList<>(); freePermits = i; } - + @Override public void release() { - if (q.peek() == null) { + if (q.peek() == null) q.poll(); - } else { + else freePermits++; - } } @Override public void acquire() throws InterruptedException { - if (freePermits > 0) { + if (freePermits > 0) freePermits--; - } else { - Object thiz = new Object(); + else { + final Object thiz = new Object(); q.offer(thiz); - while(q.contains(thiz)) { + while (q.contains(thiz)) Thread.sleep(500); - } } } } diff --git a/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMSettings.java b/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMSettings.java index 6ffbf489..c4ef8ea3 100644 --- a/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMSettings.java +++ b/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMSettings.java @@ -7,16 +7,16 @@ public class TeaVMSettings implements Settings { private boolean debug; public TeaVMSettings() { - this.debug = true; + debug = true; } - + @Override public boolean isDebugEnabled() { return debug; } @Override - public void setDebugEnabled(boolean debug) { + public void setDebugEnabled(final boolean debug) { this.debug = debug; } diff --git a/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMStorageUtils.java b/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMStorageUtils.java index d506a8fa..04a22b61 100644 --- a/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMStorageUtils.java +++ b/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMStorageUtils.java @@ -22,182 +22,178 @@ import org.teavm.jso.browser.Window; import it.cavallium.warppi.Platform.StorageUtils; public class TeaVMStorageUtils implements StorageUtils { - public boolean exists(File f) { + @Override + public boolean exists(final File f) { return f.exists(); } - public File get(String path) { + @Override + public File get(final String path) { return new File(path); } - private static String join(String[] list, String conjunction) - { - StringBuilder sb = new StringBuilder(); - boolean first = true; - for (String item : list) - { - if (first) - first = false; - else - sb.append(conjunction); - sb.append(item); - } - return sb.toString(); - } - - public File get(String... path) { - return new File(join(path, File.separator)); + private static String join(final String[] list, final String conjunction) { + final StringBuilder sb = new StringBuilder(); + boolean first = true; + for (final String item : list) { + if (first) + first = false; + else + sb.append(conjunction); + sb.append(item); + } + return sb.toString(); } - private static Map resourcesCache = new HashMap(); + @Override + public File get(final String... path) { + return new File(TeaVMStorageUtils.join(path, File.separator)); + } - public File getResource(String path) throws IOException, URISyntaxException { + private static Map resourcesCache = new HashMap<>(); + + @Override + public File getResource(final String path) throws IOException, URISyntaxException { try { File targetFile; - if (resourcesCache.containsKey(path)) { - if ((targetFile = resourcesCache.get(path)).exists()) { + if (TeaVMStorageUtils.resourcesCache.containsKey(path)) + if ((targetFile = TeaVMStorageUtils.resourcesCache.get(path)).exists()) return targetFile; - } else { - resourcesCache.remove(path); - } - } - final URL res = new URL(this.getBasePath()+path); - InputStream initialStream = res.openStream(); - byte[] buffer = new byte[initialStream.available()]; - initialStream.read(buffer); - - targetFile = File.createTempFile("res", ".bin"); - targetFile.createNewFile(); - FileOutputStream outStream = new FileOutputStream(targetFile); - outStream.write(buffer); - outStream.close(); - resourcesCache.put(path, targetFile); - return targetFile; + else + TeaVMStorageUtils.resourcesCache.remove(path); + final URL res = new URL(getBasePath() + path); + final InputStream initialStream = res.openStream(); + final byte[] buffer = new byte[initialStream.available()]; + initialStream.read(buffer); + + targetFile = File.createTempFile("res", ".bin"); + targetFile.createNewFile(); + final FileOutputStream outStream = new FileOutputStream(targetFile); + outStream.write(buffer); + outStream.close(); + TeaVMStorageUtils.resourcesCache.put(path, targetFile); + return targetFile; } catch (final java.lang.IllegalArgumentException e) { throw e; } } - public InputStream getResourceStream(String path) throws IOException, URISyntaxException { + @Override + public InputStream getResourceStream(final String path) throws IOException, URISyntaxException { try { File targetFile; - if (resourcesCache.containsKey(path)) { - if ((targetFile = resourcesCache.get(path)).exists()) { + if (TeaVMStorageUtils.resourcesCache.containsKey(path)) + if ((targetFile = TeaVMStorageUtils.resourcesCache.get(path)).exists()) return new FileInputStream(targetFile); - } else { - resourcesCache.remove(path); - } - } - final URL res = new URL(this.getBasePath()+path); - InputStream initialStream = res.openStream(); - byte[] buffer = new byte[initialStream.available()]; - initialStream.read(buffer); - - targetFile = File.createTempFile("res", ".bin"); - targetFile.createNewFile(); - FileOutputStream outStream = new FileOutputStream(targetFile); - outStream.write(buffer); - outStream.close(); - resourcesCache.put(path, targetFile); - return new FileInputStream(targetFile); + else + TeaVMStorageUtils.resourcesCache.remove(path); + final URL res = new URL(getBasePath() + path); + final InputStream initialStream = res.openStream(); + final byte[] buffer = new byte[initialStream.available()]; + initialStream.read(buffer); + + targetFile = File.createTempFile("res", ".bin"); + targetFile.createNewFile(); + final FileOutputStream outStream = new FileOutputStream(targetFile); + outStream.write(buffer); + outStream.close(); + TeaVMStorageUtils.resourcesCache.put(path, targetFile); + return new FileInputStream(targetFile); } catch (final java.lang.IllegalArgumentException e) { throw e; } } - public List readAllLines(File file) throws IOException { - Reader reader_ = new InputStreamReader(new FileInputStream(file), Charset.defaultCharset()); - BufferedReader reader = reader_ instanceof BufferedReader ? (BufferedReader) reader_ : new BufferedReader(reader_); - List list = new ArrayList(); - String line = reader.readLine(); - while (line != null) { - list.add(line); - line = reader.readLine(); - } - reader.close(); - return list; + @Override + public List readAllLines(final File file) throws IOException { + final Reader reader_ = new InputStreamReader(new FileInputStream(file), Charset.defaultCharset()); + final BufferedReader reader = reader_ instanceof BufferedReader ? (BufferedReader) reader_ : new BufferedReader(reader_); + final List list = new ArrayList<>(); + String line = reader.readLine(); + while (line != null) { + list.add(line); + line = reader.readLine(); + } + reader.close(); + return list; } - public String read(InputStream input) throws IOException { + @Override + public String read(final InputStream input) throws IOException { return IOUtils.toString(input, "UTF-8"); } - public List walk(File dir) throws IOException { - List out = new ArrayList<>(); - File[] filesList = dir.listFiles(); - if (filesList == null) { + @Override + public List walk(final File dir) throws IOException { + final List out = new ArrayList<>(); + final File[] filesList = dir.listFiles(); + if (filesList == null) out.add(dir); - } else { - for (File f : filesList) { + else + for (final File f : filesList) if (f.isDirectory()) { - if (f.canRead()) { + if (f.canRead()) out.addAll(walk(dir)); - } - } else if (f.isFile()) { - if (f.canRead()) { + } else if (f.isFile()) + if (f.canRead()) out.add(f); - } - } - } - } return out; } - public File relativize(File rulesPath, File f) { + @Override + public File relativize(final File rulesPath, final File f) { return f; } - public File resolve(File file, String string) { + @Override + public File resolve(final File file, final String string) { return new File(file.getAbsolutePath() + File.separatorChar + string); } - public File getParent(File f) { + @Override + public File getParent(final File f) { return f.getParentFile(); } - public void createDirectories(File dir) throws IOException { + @Override + public void createDirectories(final File dir) throws IOException { dir.mkdirs(); } - public void write(File f, byte[] bytes, int... options) throws IOException { + @Override + public void write(final File f, final byte[] bytes, final int... options) throws IOException { boolean create = false; - for (int opt : options) { - if (opt == StorageUtils.OpenOptionCreate) { + for (final int opt : options) + if (opt == StorageUtils.OpenOptionCreate) create = true; - } - } - if (f.exists() == false) { + if (f.exists() == false) if (create) { - if (!f.createNewFile()) { + if (!f.createNewFile()) throw new IOException("File doesn't exist, can't create it!"); - } - } else { + } else throw new IOException("File doesn't exist."); - } - } - FileOutputStream stream = new FileOutputStream(f); + final FileOutputStream stream = new FileOutputStream(f); stream.write(bytes); stream.close(); } - public List readAllLines(InputStream input) throws IOException { + @Override + public List readAllLines(final InputStream input) throws IOException { try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) { String thisLine = null; - ArrayList output = new ArrayList<>(); - while ((thisLine = buffer.readLine()) != null) { + final ArrayList output = new ArrayList<>(); + while ((thisLine = buffer.readLine()) != null) output.add(thisLine); - } return output; } } @Override public String getBasePath() { - String fullurl = Window.current().getLocation().getFullURL(); - if (fullurl.charAt(fullurl.length()-1) == '/') { - return fullurl+"resources"; - } else { - return fullurl+"/resources"; - } + final String fullurl = Window.current().getLocation().getFullURL(); + if (fullurl.charAt(fullurl.length() - 1) == '/') + return fullurl + "resources"; + else + return fullurl + "/resources"; } } diff --git a/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMURLClassLoader.java b/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMURLClassLoader.java index 105c7058..f75aef97 100644 --- a/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMURLClassLoader.java +++ b/teavm/src/main/java/it/cavallium/warppi/teavm/TeaVMURLClassLoader.java @@ -7,18 +7,18 @@ import it.cavallium.warppi.Platform.URLClassLoader; public class TeaVMURLClassLoader implements URLClassLoader { - public TeaVMURLClassLoader(URL[] urls) { - + public TeaVMURLClassLoader(final URL[] urls) { + } @Override - public Class loadClass(String name) throws ClassNotFoundException { + public Class loadClass(final String name) throws ClassNotFoundException { return null; } @Override public void close() throws IOException { - + } }