diff --git a/LICENSE b/LICENSE deleted file mode 100644 index fdddb29..0000000 --- a/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -This is free and unencumbered software released into the public domain. - -Anyone is free to copy, modify, publish, use, compile, sell, or -distribute this software, either in source code form or as a compiled -binary, for any purpose, commercial or non-commercial, and by any -means. - -In jurisdictions that recognize copyright laws, the author or authors -of this software dedicate any and all copyright interest in the -software to the public domain. We make this dedication for the benefit -of the public at large and to the detriment of our heirs and -successors. We intend this dedication to be an overt act of -relinquishment in perpetuity of all present and future rights to this -software under copyright law. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR -OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. - -For more information, please refer to diff --git a/pisi/unitedmeows/yystal/logger/impl/YLogger.java b/pisi/unitedmeows/yystal/logger/impl/YLogger.java index aa6f8ea..d758b82 100644 --- a/pisi/unitedmeows/yystal/logger/impl/YLogger.java +++ b/pisi/unitedmeows/yystal/logger/impl/YLogger.java @@ -2,7 +2,6 @@ import org.fusesource.jansi.Ansi; import org.fusesource.jansi.AnsiConsole; -import org.lwjglx.Sys; import pisi.unitedmeows.yystal.file.YFile; import pisi.unitedmeows.yystal.logger.ILogger; diff --git a/pisi/unitedmeows/yystal/networking/client/extension/impl/CTcpFixedSize.java b/pisi/unitedmeows/yystal/networking/client/extension/impl/CTcpFixedSize.java index 687bf91..58fdcb6 100644 --- a/pisi/unitedmeows/yystal/networking/client/extension/impl/CTcpFixedSize.java +++ b/pisi/unitedmeows/yystal/networking/client/extension/impl/CTcpFixedSize.java @@ -6,6 +6,7 @@ import pisi.unitedmeows.yystal.utils.MemoryWriter; import java.io.DataInputStream; +import java.io.IOException; public class CTcpFixedSize extends CTcpExtension { @@ -21,6 +22,9 @@ public void onDataSend(ref data, ref send) { } data.set(memoryWriter.getBytes()); send.set(true); + try { + memoryWriter.close(); + } catch (IOException e) {} } @Override diff --git a/pisi/unitedmeows/yystal/networking/client/extension/impl/CTcpLineRead.java b/pisi/unitedmeows/yystal/networking/client/extension/impl/CTcpLineRead.java index 970f436..90887f6 100644 --- a/pisi/unitedmeows/yystal/networking/client/extension/impl/CTcpLineRead.java +++ b/pisi/unitedmeows/yystal/networking/client/extension/impl/CTcpLineRead.java @@ -37,8 +37,6 @@ public void onPreDataReceive(DataInputStream inputStream, ref cancelDef } cancelDefaultReader.set(true); readData.set(readLine.getBytes(StandardCharsets.UTF_8)); - } catch (Exception ex) { - - } + } catch (Exception ex) {} } } diff --git a/pisi/unitedmeows/yystal/networking/server/extension/impl/STcpFixedSize.java b/pisi/unitedmeows/yystal/networking/server/extension/impl/STcpFixedSize.java index af82dbb..4077afc 100644 --- a/pisi/unitedmeows/yystal/networking/server/extension/impl/STcpFixedSize.java +++ b/pisi/unitedmeows/yystal/networking/server/extension/impl/STcpFixedSize.java @@ -7,6 +7,7 @@ import pisi.unitedmeows.yystal.utils.MemoryWriter; import java.io.DataInputStream; +import java.io.IOException; public class STcpFixedSize extends STcpExtension { @@ -21,6 +22,7 @@ public void onPreDataReceive(YSocketClient client, DataInputStream inputStream, inputStream.read(data); cancelDefaultReader.set(true); readData.set(data); + } catch (Exception ex) { } } @@ -34,6 +36,9 @@ public void onDataSend(YSocketClient client, ref data, ref send memoryWriter.write(rawData); data.set(memoryWriter.getBytes()); send.set(true); + try { + memoryWriter.close(); + } catch (IOException e) {} } catch (Exception ex) { } } diff --git a/pisi/unitedmeows/yystal/ui/YWindow.java b/pisi/unitedmeows/yystal/ui/YWindow.java index 504af11..44a03af 100644 --- a/pisi/unitedmeows/yystal/ui/YWindow.java +++ b/pisi/unitedmeows/yystal/ui/YWindow.java @@ -27,6 +27,7 @@ import pisi.unitedmeows.yystal.utils.Vector2f; public class YWindow extends YContainer { + private final Vector2f /* yystal vector2f :D.d:D */ mouseCoords = new Vector2f(-1F, -1F); private final Vector2f mouseDelta = new Vector2f(-1F, -1F); private final String title; diff --git a/pisi/unitedmeows/yystal/ui/font/Batch.java b/pisi/unitedmeows/yystal/ui/font/Batch.java index 5a96e84..ddd60b6 100644 --- a/pisi/unitedmeows/yystal/ui/font/Batch.java +++ b/pisi/unitedmeows/yystal/ui/font/Batch.java @@ -92,10 +92,10 @@ public void addCharacter(final float x, final float y, final float scale, final final float y0 = y; final float x1 = x + scale * charInfo.width; final float y1 = y + scale * charInfo.height; - final float ux0 = charInfo.textureCoordinates[0].x; - final float uy0 = charInfo.textureCoordinates[0].y; - final float ux1 = charInfo.textureCoordinates[1].x; - final float uy1 = charInfo.textureCoordinates[1].y; + final float ux0 = charInfo.textureCoordinates[0].getX(); + final float uy0 = charInfo.textureCoordinates[0].getY(); + final float ux1 = charInfo.textureCoordinates[1].getX(); + final float uy1 = charInfo.textureCoordinates[1].getY(); int index = size * 7; vertices[index] = x1; vertices[index + 1] = y0; diff --git a/pisi/unitedmeows/yystal/ui/font/data/CharInfo.java b/pisi/unitedmeows/yystal/ui/font/data/CharInfo.java index fc7704f..67f171b 100644 --- a/pisi/unitedmeows/yystal/ui/font/data/CharInfo.java +++ b/pisi/unitedmeows/yystal/ui/font/data/CharInfo.java @@ -1,6 +1,7 @@ package pisi.unitedmeows.yystal.ui.font.data; -import org.joml.Vector2f; + +import pisi.unitedmeows.yystal.utils.Vector2f; public class CharInfo { public int sourceX; diff --git a/pisi/unitedmeows/yystal/ui/utils/Rectangle.java b/pisi/unitedmeows/yystal/ui/utils/Rectangle.java index 4571c47..aba2e64 100644 --- a/pisi/unitedmeows/yystal/ui/utils/Rectangle.java +++ b/pisi/unitedmeows/yystal/ui/utils/Rectangle.java @@ -1,5 +1,8 @@ package pisi.unitedmeows.yystal.ui.utils; + +import org.joml.Vector4f; + import static org.lwjgl.opengl.GL11.GL_BLEND; import static org.lwjgl.opengl.GL11.GL_FLAT; import static org.lwjgl.opengl.GL11.GL_LINE_SMOOTH; @@ -19,7 +22,6 @@ import static org.lwjgl.opengl.GL11.glShadeModel; import static org.lwjgl.opengl.GL11.glVertex2d; -import org.joml.Vector4f; public class Rectangle { public Vector4f vector; diff --git a/pisi/unitedmeows/yystal/utils/Vector3.java b/pisi/unitedmeows/yystal/utils/Vector3.java index 7e34717..865a0f5 100644 --- a/pisi/unitedmeows/yystal/utils/Vector3.java +++ b/pisi/unitedmeows/yystal/utils/Vector3.java @@ -1,2 +1,26 @@ -package pisi.unitedmeows.yystal.utils;public class Vector3 { +package pisi.unitedmeows.yystal.utils; + +public class Vector3 { + + private F first; + private S second; + private T third; + + public Vector3(F _first, S _second, T _third) { + first = _first; + second = _second; + third = _third; + } + + public F first() { + return first; + } + + public S second() { + return second; + } + + public T third() { + return third; + } } diff --git a/pisi/unitedmeows/yystal/utils/Vector4f.java b/pisi/unitedmeows/yystal/utils/Vector4f.java index 32616d0..ccb638b 100644 --- a/pisi/unitedmeows/yystal/utils/Vector4f.java +++ b/pisi/unitedmeows/yystal/utils/Vector4f.java @@ -1,2 +1,4 @@ -package pisi.unitedmeows.yystal.utils;public class Vector4f { +package pisi.unitedmeows.yystal.utils; + +public class Vector4f { } diff --git a/pisi/unitedmeows/yystal/yap/YAppServer.java b/pisi/unitedmeows/yystal/yap/YAppServer.java index cc0e250..95b6c63 100644 --- a/pisi/unitedmeows/yystal/yap/YAppServer.java +++ b/pisi/unitedmeows/yystal/yap/YAppServer.java @@ -80,10 +80,6 @@ protected static int findAvailablePort() { return -1; } - /* - app => { name: 'Skuxx', version: 1.8, id:'$353tkşlrdgdfgdfg' } - */ - protected String createAppIntroduction() { SxfFile file = new SxfFile(); SxfDataBlock app = new SxfDataBlock(); diff --git a/src/pisi/unitedmeows/yystal/YSettings.java b/src/pisi/unitedmeows/yystal/YSettings.java deleted file mode 100644 index 68d5b61..0000000 --- a/src/pisi/unitedmeows/yystal/YSettings.java +++ /dev/null @@ -1,9 +0,0 @@ -package pisi.unitedmeows.yystal; - -public enum YSettings { - TASKWORKER_FETCH_DELAY, - TASKPOOL_CONTROL_CHECK_DELAY, - TASK_AWAIT_DELAY, - TCP_CLIENT_WRITE_DELAY, - TCP_CLIENT_QUEUE_CHECK_DELAY; -} diff --git a/src/pisi/unitedmeows/yystal/YYStal.java b/src/pisi/unitedmeows/yystal/YYStal.java deleted file mode 100644 index b6138ba..0000000 --- a/src/pisi/unitedmeows/yystal/YYStal.java +++ /dev/null @@ -1,137 +0,0 @@ -package pisi.unitedmeows.yystal; - -import pisi.unitedmeows.yystal.clazz.function; -import pisi.unitedmeows.yystal.clazz.out; -import pisi.unitedmeows.yystal.clazz.ref; -import pisi.unitedmeows.yystal.clazz.valuelock; -import pisi.unitedmeows.yystal.exception.YEx; -import pisi.unitedmeows.yystal.exception.YExManager; -import pisi.unitedmeows.yystal.hook.YString; -import pisi.unitedmeows.yystal.parallel.ITaskPool; -import pisi.unitedmeows.yystal.parallel.pools.BasicTaskPool; -import pisi.unitedmeows.yystal.sql.YSQLCommand; -import pisi.unitedmeows.yystal.ui.YWindow; -import pisi.unitedmeows.yystal.utils.Pair; -import pisi.unitedmeows.yystal.utils.Stopwatch; -import pisi.unitedmeows.yystal.utils.Types; - -import java.util.HashMap; - -public class YYStal { - - private static ITaskPool currentPool; - private static final HashMap stopWatchMap; - private static final HashMap settings; - private static final Thread mainThread; - private static final HashMap> valueLocks; - private static final HashMap windowMap; - - static { - mainThread = Thread.currentThread(); - valueLocks = new HashMap<>(); - stopWatchMap = new HashMap<>(); - settings = new HashMap<>(); - windowMap = new HashMap<>(); - setCurrentPool(new BasicTaskPool(5, 12)); - settings.put(YSettings.TASKWORKER_FETCH_DELAY, 1L); - settings.put(YSettings.TASKPOOL_CONTROL_CHECK_DELAY, 3L); - settings.put(YSettings.TASK_AWAIT_DELAY, 1L); - settings.put(YSettings.TCP_CLIENT_QUEUE_CHECK_DELAY, 1L); - settings.put(YSettings.TCP_CLIENT_WRITE_DELAY, 12L); - } - - public static void setCurrentPool(ITaskPool taskPool) { - if (currentPool != null) { - currentPool.unregister(); - } - currentPool = taskPool; - currentPool.register(); - } - - - public static void pop(YEx ex) { - YExManager.pop(ex); - } - - public static void shot(function func, function pop) { - YExManager.shot(func, pop); - } - - public static YEx lastEx() { - return YExManager.lastEx(); - } - - public static void startWatcher() { - stopWatchMap.computeIfAbsent(Thread.currentThread(), x -> new Stopwatch()).reset(); - } - - public static long stopWatcher() { - return stopWatchMap.computeIfAbsent(Thread.currentThread(), x -> new Stopwatch()).elapsed(); - } - - public static YSQLCommand sqlCommand(String command, Object... params) { - YSQLCommand ysqlCommand = new YSQLCommand(command); - for (Object param : params) { - ysqlCommand.put(param); - } - return ysqlCommand; - } - - public static ref reference(X initValue) { - return new ref(initValue); - } - - public static Pair pair(F first, S second) { - return new Pair<>(first, second); - } - - public static valuelock value_lock(final String name) { - if (valueLocks.containsKey(name)) - return (valuelock) valueLocks.get(name); - - valuelock lock = new valuelock<>(); - valueLocks.put(name, lock); - lock.__setup(); - - - - return lock; - } - - public static int sizeof(Class clazz) { - return Types.sizeof(clazz); - } - - public static void times(int count, Runnable runnable) { - for (int i = 0; i < count; i++) { - runnable.run(); - } - } - - public static YWindow currentWindow() { - return windowMap.getOrDefault(Thread.currentThread(), null); - } - - public static void registerWindow(YWindow window) { - windowMap.put(Thread.currentThread(), window); - } - - public static out out() { - return new out(); - } - - public static X setting(YSettings setting) { - return (X) settings.get(setting); - } - - public static YString yString(String str) { return new YString(str); } - - public static Thread mainThread() { - return mainThread; - } - - public static ITaskPool taskPool() { - return currentPool; - } - -} diff --git a/src/pisi/unitedmeows/yystal/clazz/HookClass.java b/src/pisi/unitedmeows/yystal/clazz/HookClass.java deleted file mode 100644 index 5e08fb8..0000000 --- a/src/pisi/unitedmeows/yystal/clazz/HookClass.java +++ /dev/null @@ -1,9 +0,0 @@ -package pisi.unitedmeows.yystal.clazz; - -public class HookClass { - protected X hooked; - - protected X getHooked() { - return hooked; - } -} diff --git a/src/pisi/unitedmeows/yystal/clazz/delegate.java b/src/pisi/unitedmeows/yystal/clazz/delegate.java deleted file mode 100644 index 03984e0..0000000 --- a/src/pisi/unitedmeows/yystal/clazz/delegate.java +++ /dev/null @@ -1,3 +0,0 @@ -package pisi.unitedmeows.yystal.clazz; - -public interface delegate { } \ No newline at end of file diff --git a/src/pisi/unitedmeows/yystal/clazz/event.java b/src/pisi/unitedmeows/yystal/clazz/event.java deleted file mode 100644 index a3eeb10..0000000 --- a/src/pisi/unitedmeows/yystal/clazz/event.java +++ /dev/null @@ -1,57 +0,0 @@ -package pisi.unitedmeows.yystal.clazz; - -import pisi.unitedmeows.yystal.exception.YExManager; -import pisi.unitedmeows.yystal.exception.impl.YexNullPtr; -import pisi.unitedmeows.yystal.utils.Pair; -import pisi.unitedmeows.yystal.utils.YRandom; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; - -public class event { - - protected HashMap> delegateMap; - - public event() { - delegateMap = new HashMap<>(); - } - - public void fire(Object... params) { - for (Pair bound : delegateMap.values()) { - try { - - bound.item2().invoke(bound.item1(), params); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } - - public void free(int delegateId) { - delegateMap.remove(delegateId); - } - - public int bind(X del) { - int delegateId; - - do { - delegateId = YRandom.BASIC.nextInRange(0, 217300); - } while (delegateMap.containsKey(delegateId)); - - try { - - - Method method = del.getClass().getDeclaredMethods()[0]; - if (!method.isAccessible()) { - method.setAccessible(true); - } - delegateMap.put(delegateId ,new Pair<>(del, method)); - return delegateId; - } catch (NullPointerException ex) { - YExManager.pop(new YexNullPtr("Delegate method couldn't be found " + del.getClass())); - return -1; - } - } -} diff --git a/src/pisi/unitedmeows/yystal/clazz/function.java b/src/pisi/unitedmeows/yystal/clazz/function.java deleted file mode 100644 index c04ac1f..0000000 --- a/src/pisi/unitedmeows/yystal/clazz/function.java +++ /dev/null @@ -1,5 +0,0 @@ -package pisi.unitedmeows.yystal.clazz; - -public abstract class function { - public abstract void run(); -} diff --git a/src/pisi/unitedmeows/yystal/clazz/mutex.java b/src/pisi/unitedmeows/yystal/clazz/mutex.java deleted file mode 100644 index b0f1c3a..0000000 --- a/src/pisi/unitedmeows/yystal/clazz/mutex.java +++ /dev/null @@ -1,18 +0,0 @@ -package pisi.unitedmeows.yystal.clazz; - -import pisi.unitedmeows.yystal.utils.kThread; - -public class mutex { - - private boolean locked; - - public void lock() { - locked = true; - kThread.sleep_till(() -> { return locked; }); - } - - public void unlock() { - locked = false; - } - -} diff --git a/src/pisi/unitedmeows/yystal/clazz/out.java b/src/pisi/unitedmeows/yystal/clazz/out.java deleted file mode 100644 index 0781ae2..0000000 --- a/src/pisi/unitedmeows/yystal/clazz/out.java +++ /dev/null @@ -1,14 +0,0 @@ -package pisi.unitedmeows.yystal.clazz; - -/* the feature in c# */ -/* allows you get value from method as a parameter */ -public class out extends HookClass { - - public X get() { - return hooked; - } - - public void set(X value) { - hooked = value; - } -} diff --git a/src/pisi/unitedmeows/yystal/clazz/prop.java b/src/pisi/unitedmeows/yystal/clazz/prop.java deleted file mode 100644 index d6e477b..0000000 --- a/src/pisi/unitedmeows/yystal/clazz/prop.java +++ /dev/null @@ -1,11 +0,0 @@ -package pisi.unitedmeows.yystal.clazz; - -public class prop { - protected X value; - - public prop() {} - public prop(X _value) { value = _value; } - - public void set(X newValue) { value = newValue;} - public X get() { return value; } -} diff --git a/src/pisi/unitedmeows/yystal/clazz/ref.java b/src/pisi/unitedmeows/yystal/clazz/ref.java deleted file mode 100644 index 1c5993c..0000000 --- a/src/pisi/unitedmeows/yystal/clazz/ref.java +++ /dev/null @@ -1,20 +0,0 @@ -package pisi.unitedmeows.yystal.clazz; - -/* similar like out but this time you have to initialize before sending as a parameter */ -/* the feature in c# */ -public class ref extends HookClass { - - public ref() {} - - public ref(X value) { - set(value); - } - - public X get() { - return hooked; - } - - public void set(X value) { - hooked = value; - } -} diff --git a/src/pisi/unitedmeows/yystal/clazz/shared.java b/src/pisi/unitedmeows/yystal/clazz/shared.java deleted file mode 100644 index eb7cb69..0000000 --- a/src/pisi/unitedmeows/yystal/clazz/shared.java +++ /dev/null @@ -1,27 +0,0 @@ -package pisi.unitedmeows.yystal.clazz; - -import pisi.unitedmeows.yystal.utils.YRandom; - -import java.util.HashMap; - -public class shared{ - private final HashMap values = new HashMap<>(); - - public X get(byte data) { - return values.getOrDefault(data, null); - } - - public byte put(X obj) { - byte identifier; - do { - identifier = YRandom.BASIC.nextByte(); - } while (values.containsKey(identifier)); - - values.put(identifier, obj); - return identifier; - } - - public void remove(byte identifier) { - values.remove(identifier); - } -} diff --git a/src/pisi/unitedmeows/yystal/clazz/soulbound.java b/src/pisi/unitedmeows/yystal/clazz/soulbound.java deleted file mode 100644 index 7ce93bf..0000000 --- a/src/pisi/unitedmeows/yystal/clazz/soulbound.java +++ /dev/null @@ -1,68 +0,0 @@ -package pisi.unitedmeows.yystal.clazz; - -import pisi.unitedmeows.yystal.parallel.Async; -import pisi.unitedmeows.yystal.parallel.Promise; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.function.Function; - -public abstract class soulbound { - - protected HashMap boundMap; - protected Promise promise; - private long checkTimer; - - public soulbound(long _checkTimer) { - checkTimer = _checkTimer; - boundMap = new HashMap<>(); - promise = Async.async_loop(() -> { - Iterator> entryIterator = boundMap.entrySet().iterator(); - while (entryIterator.hasNext()) { - Map.Entry entry = entryIterator.next(); - if (breakBound(entry.getKey(), entry.getValue())) { - onRemove(entry.getKey(), entry.getValue()); - entryIterator.remove(); - } - } - }, _checkTimer); - } - - public soulbound() { - this(1000L); - } - - public X get(I instance) { - return boundMap.get(instance); - } - - public void add(I instance, X value) { - boundMap.put(instance, value); - } - - public void remove(I instance) { - boundMap.remove(instance); - } - - public void onRemove(I instance, X value) { - - } - - public X computeIfAbsent(I instance, Function function) { - return boundMap.computeIfAbsent(instance, function); - } - - public void stop() { - promise.stop(); - promise = null; - } - - public void start() { - promise = Async.async_loop(() -> { - boundMap.entrySet().removeIf(entry -> breakBound(entry.getKey(), entry.getValue())); - }, checkTimer); - } - - public abstract boolean breakBound(I instance, X value); -} diff --git a/src/pisi/unitedmeows/yystal/clazz/valuelock.java b/src/pisi/unitedmeows/yystal/clazz/valuelock.java deleted file mode 100644 index d0e2a93..0000000 --- a/src/pisi/unitedmeows/yystal/clazz/valuelock.java +++ /dev/null @@ -1,24 +0,0 @@ -package pisi.unitedmeows.yystal.clazz; - -import pisi.unitedmeows.yystal.YYStal; -import pisi.unitedmeows.yystal.utils.kThread; - -/* locks the current thread until it get freed by another thread by getting a value */ -public class valuelock extends HookClass { - - private boolean locked; - - public void __setup() { - locked = true; - kThread.sleep_till(() -> locked); - } - - public void free(X _value) { - hooked = _value; - locked = false; - } - - public X get() { - return hooked; - } -} diff --git a/src/pisi/unitedmeows/yystal/exception/YEx.java b/src/pisi/unitedmeows/yystal/exception/YEx.java deleted file mode 100644 index 8843d1d..0000000 --- a/src/pisi/unitedmeows/yystal/exception/YEx.java +++ /dev/null @@ -1,6 +0,0 @@ -package pisi.unitedmeows.yystal.exception; - -public abstract class YEx { - public abstract String getMessage(); - public void printMessage() { System.err.println(getMessage()); } -} diff --git a/src/pisi/unitedmeows/yystal/exception/YExManager.java b/src/pisi/unitedmeows/yystal/exception/YExManager.java deleted file mode 100644 index f4a06b8..0000000 --- a/src/pisi/unitedmeows/yystal/exception/YExManager.java +++ /dev/null @@ -1,26 +0,0 @@ -package pisi.unitedmeows.yystal.exception; - -import pisi.unitedmeows.yystal.clazz.function; - -import java.util.HashMap; - -public class YExManager { - - private static HashMap lastExceptionMap = new HashMap<>(); - - public static X lastEx() { - return (X) lastExceptionMap.getOrDefault(Thread.currentThread(), null); - } - - public static void pop(YEx ex) { - lastExceptionMap.put(Thread.currentThread(), ex); - } - - public static void shot(function func, function pop) { - YEx lastEx = lastEx(); - func.run(); - YEx current = lastEx(); - if (current != lastEx) - pop.run(); - } -} diff --git a/src/pisi/unitedmeows/yystal/exception/impl/YexIO.java b/src/pisi/unitedmeows/yystal/exception/impl/YexIO.java deleted file mode 100644 index 50c8d42..0000000 --- a/src/pisi/unitedmeows/yystal/exception/impl/YexIO.java +++ /dev/null @@ -1,21 +0,0 @@ -package pisi.unitedmeows.yystal.exception.impl; - -import pisi.unitedmeows.yystal.exception.YEx; - -public class YexIO extends YEx { - - private final String message; - - public YexIO(String _message) { - message = _message; - } - - public YexIO() { - this("Received IO Exception"); - } - - @Override - public String getMessage() { - return message; - } -} diff --git a/src/pisi/unitedmeows/yystal/exception/impl/YexIllegalAccess.java b/src/pisi/unitedmeows/yystal/exception/impl/YexIllegalAccess.java deleted file mode 100644 index 40952a0..0000000 --- a/src/pisi/unitedmeows/yystal/exception/impl/YexIllegalAccess.java +++ /dev/null @@ -1,16 +0,0 @@ -package pisi.unitedmeows.yystal.exception.impl; - -import pisi.unitedmeows.yystal.exception.YEx; - -public class YexIllegalAccess extends YEx { - - private final String message; - public YexIllegalAccess(final String _message) { - message = _message; - } - - @Override - public String getMessage() { - return message; - } -} diff --git a/src/pisi/unitedmeows/yystal/exception/impl/YexNullPtr.java b/src/pisi/unitedmeows/yystal/exception/impl/YexNullPtr.java deleted file mode 100644 index 16dda43..0000000 --- a/src/pisi/unitedmeows/yystal/exception/impl/YexNullPtr.java +++ /dev/null @@ -1,21 +0,0 @@ -package pisi.unitedmeows.yystal.exception.impl; - -import pisi.unitedmeows.yystal.exception.YEx; - -public class YexNullPtr extends YEx { - - private final String message; - - public YexNullPtr(String _message) { - message = _message; - } - - public YexNullPtr() { - this("Received Null Exception"); - } - - @Override - public String getMessage() { - return message; - } -} diff --git a/src/pisi/unitedmeows/yystal/file/YDirectory.java b/src/pisi/unitedmeows/yystal/file/YDirectory.java deleted file mode 100644 index e85f3c0..0000000 --- a/src/pisi/unitedmeows/yystal/file/YDirectory.java +++ /dev/null @@ -1,54 +0,0 @@ -package pisi.unitedmeows.yystal.file; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -public class YDirectory { - - private File file; - - public YDirectory(File _file) { - file = _file; - } - - public YDirectory(String _path) { - this(new File(_path)); - } - - public YDirectory(String parent, String fileName) { - this(new File(parent, fileName)); - } - - public YDirectory parent() { - return new YDirectory(file.getParentFile()); - } - - public List listFiles() { - List files = new ArrayList<>(); - for (File listFile : file.listFiles(filter -> filter.isFile())) { - files.add(new YFile(listFile)); - } - return files; - } - - public List list() { - List list = new ArrayList<>(); - for (File obj : file.listFiles(filter -> filter.isDirectory())) { - list.add(new YDirectory(obj)); - } - return list; - } - - public List listDirectories() { - List directories = new ArrayList<>(); - for (File listDirectory : file.listFiles(filter -> filter.isDirectory())) { - directories.add(new YDirectory(listDirectory)); - } - return directories; - } - - public File raw() { - return file; - } -} diff --git a/src/pisi/unitedmeows/yystal/file/YFile.java b/src/pisi/unitedmeows/yystal/file/YFile.java deleted file mode 100644 index 8efa996..0000000 --- a/src/pisi/unitedmeows/yystal/file/YFile.java +++ /dev/null @@ -1,155 +0,0 @@ -package pisi.unitedmeows.yystal.file; - -import pisi.unitedmeows.yystal.YYStal; -import pisi.unitedmeows.yystal.exception.YEx; -import pisi.unitedmeows.yystal.exception.impl.YexIO; - -import java.io.*; -import java.util.ArrayList; -import java.util.List; - -public class YFile { - - private String path; - private File file; - - public YFile(String _path) { - this(new File(_path)); - } - - public YFile(File _file) { - file = _file; - path = file.getAbsolutePath(); - } - - public YFile(String _directory, String _fileName) { - this(new File(_directory, _fileName)); - } - - public void create() { - try { - file.createNewFile(); - } catch (IOException e) { - YYStal.pop(new YexIO("Couldn't create a new file PATH: " + path)); - } - } - - public void writeAll(String input) { - try { - FileWriter myWriter = new FileWriter(file); - myWriter.write(input); - myWriter.close(); - } catch (IOException ex) { - YYStal.pop(new YexIO("Error while YFile:writeAll (couldn't write to file)")); - } - } - - public void writeAll(List input) { - StringBuilder stringBuilder = new StringBuilder(); - for (int i = 0; i < input.size(); i++) { - stringBuilder.append(input.get(i)); - stringBuilder.append(System.lineSeparator()); - } - writeAll(stringBuilder.toString()); - } - - public void writeAll(String[] input) { - StringBuilder stringBuilder = new StringBuilder(); - for (int i = 0; i < input.length; i++) { - stringBuilder.append(input[i]); - stringBuilder.append(System.lineSeparator()); - } - writeAll(stringBuilder.toString()); - } - - public void write(List input) { - StringBuilder stringBuilder = new StringBuilder(); - for (int i = 0; i < input.size(); i++) { - stringBuilder.append(input.get(i)); - stringBuilder.append(System.lineSeparator()); - } - - write(stringBuilder.toString()); - } - - public void write(String[] input) { - StringBuilder stringBuilder = new StringBuilder(); - for (int i = 0; i < input.length; i++) { - stringBuilder.append(input[i]); - stringBuilder.append(System.lineSeparator()); - } - - write(stringBuilder.toString()); - } - - public void write(String input) { - try { - FileWriter myWriter = new FileWriter(file, true); - - myWriter.write(input); - myWriter.close(); - } catch (IOException ex) { - YYStal.pop(new YexIO("Error while YFile:write (couldn't write to file)")); - } - } - - public List readAllLines() - { - List readContent = new ArrayList<>(); - try - { - BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8")); - String str; - while ((str = in.readLine()) != null) - { - readContent.add(str); - } - in.close(); - } - catch (Exception e) - { - YYStal.pop(new YexIO("Error while YFile:readAllText (couldn't read the file)")); - } - return readContent; - } - - public String readAllText() - { - StringBuilder stringBuilder = new StringBuilder(); - - try - { - BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8")); - String str; - while ((str = in.readLine()) != null) - { - stringBuilder.append(str).append(System.lineSeparator()); - } - in.close(); - } - catch (Exception e) - { - YYStal.pop(new YexIO("Error while YFile:readAllText (couldn't read the file)")); - } - return stringBuilder.toString(); - } - - public boolean rename(String newName) { - File newFile = new File(file.getParentFile().getAbsoluteFile(), newName); - if (file.renameTo(file)) { - file = newFile; - return true; - } else { - YYStal.pop(new YexIO("Error while YFile:reanme (couldn't rename file to " + newName + ")")); - return false; - } - } - - public File file() { - return file; - } - - public boolean delete() { - return file.delete(); - } -} diff --git a/src/pisi/unitedmeows/yystal/file/YFileLock.java b/src/pisi/unitedmeows/yystal/file/YFileLock.java deleted file mode 100644 index 8f3934c..0000000 --- a/src/pisi/unitedmeows/yystal/file/YFileLock.java +++ /dev/null @@ -1,52 +0,0 @@ -package pisi.unitedmeows.yystal.file; - -import pisi.unitedmeows.yystal.exception.YExManager; -import pisi.unitedmeows.yystal.exception.impl.YexIO; - -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.nio.channels.FileChannel; -import java.nio.channels.FileLock; - -public class YFileLock { - - private File file; - private FileLock lock; - - public YFileLock(File _file) { - file = _file; - } - - public YFileLock(YFile yFile) { - this(yFile.file()); - } - - public boolean lock() { - FileChannel channel; - try { - channel = new RandomAccessFile(file, "rw").getChannel(); - } catch (IOException ex) { - YExManager.pop(new YexIO("Couldn't get the file channel " + file.getAbsolutePath())); - return false; - } - - try { - lock = channel.lock(); - return true; - } catch (IOException e) { - YExManager.pop(new YexIO("Couldn't lock the file " + file.getAbsolutePath())); - return false; - } - } - - public boolean free() { - try { - lock.close(); - return true; - } catch (Exception ex) { - YExManager.pop(new YexIO("Couldn't free the file " + file.getAbsolutePath())); - return false; - } - } -} diff --git a/src/pisi/unitedmeows/yystal/hook/YString.java b/src/pisi/unitedmeows/yystal/hook/YString.java deleted file mode 100644 index 5c262dd..0000000 --- a/src/pisi/unitedmeows/yystal/hook/YString.java +++ /dev/null @@ -1,112 +0,0 @@ -package pisi.unitedmeows.yystal.hook; -import pisi.unitedmeows.yystal.clazz.HookClass; - -import java.lang.StringBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -public class YString extends HookClass { - - public static final String EMPTY_R = ""; - public static final YString EMPTY = new YString(""); - - private boolean changed; - private String currentValue; - - public YString(StringBuilder stringBuilder) { - hooked = stringBuilder; - changed = true; - } - - public YString(String initial) { - hooked = new StringBuilder(initial); - changed = true; - } - - public YString add(String string) - { - changed = true; - hooked.append(string); - return this; - } - - public YString add(YString string) { - return add(string.toString()); - } - - public YString replaceFirst(char character, String toReplace) { - char lastChar = 'Y'; - int lastIndex = 0; - String text = currentValue(); - StringBuilder stringBuilder = new StringBuilder(); - boolean replaced = false; - for (int i = 0; i < text.length(); i++) { - char currentChar = text.charAt(i); - if (currentChar == '\\' && text.length() > i + 1) { - if (text.charAt(i + 1) != character) - stringBuilder.append(text.charAt(i)); - } else if (lastChar != '\\' && currentChar == character) { - stringBuilder.append(toReplace); - lastIndex = i; - replaced = true; - break; - } else { - stringBuilder.append(text.charAt(i)); - } - lastChar = text.charAt(i); - } - - if (replaced && lastIndex + 1 < text.length()) { - stringBuilder.append(text.substring(lastIndex + 1)); - } - return new YString(stringBuilder); - } - - - public String substring(int start) { - return hooked.substring(start); - } - - public YString substringY(int start) { - return new YString(hooked.substring(start)); - } - - public YString substringY(int start, int end) { - return new YString(hooked.substring(start, end)); - } - - - public YString replace(String text, String toReplace) { - hooked = new StringBuilder(hooked.toString().replaceAll(text, toReplace)); - changed = true; - return this; - } - - public YString remove(String text) { - return replace(text, EMPTY_R); - } - - public String substring(int start, int end) { - return hooked.substring(start, end); - } - - public List lines() { - String temp = currentValue().replace("\r\n", "\n"); - if (!temp.contains("\n")) { - return Collections.singletonList(currentValue()); - } - - return Arrays.asList(temp.split("\n")); - } - - @Override - public String toString() { - return currentValue(); - } - - protected String currentValue() { - return changed ? (currentValue = hooked.toString()) : currentValue; - } -} diff --git a/src/pisi/unitedmeows/yystal/logger/ILogger.java b/src/pisi/unitedmeows/yystal/logger/ILogger.java deleted file mode 100644 index cfd3fbe..0000000 --- a/src/pisi/unitedmeows/yystal/logger/ILogger.java +++ /dev/null @@ -1,10 +0,0 @@ -package pisi.unitedmeows.yystal.logger; - -public interface ILogger { - void warn(String text); - void info(String text); - void print(String text); - void fatal(String text); - void debug(String text); - void log(Enum type, String text); -} diff --git a/src/pisi/unitedmeows/yystal/logger/impl/YLogger.java b/src/pisi/unitedmeows/yystal/logger/impl/YLogger.java deleted file mode 100644 index d758b82..0000000 --- a/src/pisi/unitedmeows/yystal/logger/impl/YLogger.java +++ /dev/null @@ -1,192 +0,0 @@ -package pisi.unitedmeows.yystal.logger.impl; - -import org.fusesource.jansi.Ansi; -import org.fusesource.jansi.AnsiConsole; -import pisi.unitedmeows.yystal.file.YFile; -import pisi.unitedmeows.yystal.logger.ILogger; - -import java.io.File; -import java.time.LocalDateTime; -import java.util.*; - -public class YLogger implements ILogger { - - private Time time = Time.MILLISECONDS; - private final Class clazz; - private String name; - private boolean prefix; - private boolean save; - private int bufferSize; - private YFile file; - private String[] buffer; - private boolean colored = false; - private int bufferIndex; - - public YLogger(final Class _clazz) { - clazz = _clazz; - name = "[" + clazz.getSimpleName().toUpperCase(Locale.ROOT) + "]"; - } - - public YLogger(final Class _clazz, final String _name) { - clazz = _clazz; - name = "[" + _name + "]"; - } - - - private void post(String text) { - final StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("[").append(generateTime()).append("] "); - if (prefix) { - stringBuilder.append(name).append(" "); - } - stringBuilder.append(text); - - if (save) { - buffer[bufferIndex++] = stringBuilder.toString(); - if (bufferIndex >= bufferSize) { - flush(); - } - } - } - - private void flush() { - file.write(buffer); - bufferIndex = 0; - } - - @Override - public void info(String text) { - if (colored) { - System.out.print(Ansi.ansi().eraseScreen().fg(Ansi.Color.YELLOW).a("[").a(generateTime()).a("] ")); - - if (prefix) { - System.out.print(name); - System.out.print(" "); - } - System.out.print("[INFO] "); - System.out.println(text); - Ansi.ansi().reset(); - } else { - final StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("[").append(generateTime()).append("] "); - if (prefix) { - stringBuilder.append(name).append(" "); - } - stringBuilder.append("[INFO] "); - stringBuilder.append(text); - System.out.println(stringBuilder.toString()); - } - post(text); - } - - @Override - public void warn(String text) { - - } - - @Override - public void print(String text) { - - } - - @Override - public void fatal(String text) { - - } - - @Override - public void debug(String text) { - - } - - @Override - public void log(Enum type, String text) { - /* do nothing */ - } - - private String generateTime() { - switch (time) { - case MILLISECONDS: - return String.valueOf(System.currentTimeMillis()); - - case HOUR_MINUTES: { - LocalDateTime localDateTime = LocalDateTime.now(); - return localDateTime.getHour() + ":" + localDateTime.getMinute(); - } - case HOUR_MINUTES_SECONDS: { - LocalDateTime localDateTime = LocalDateTime.now(); - return localDateTime.getHour() + ":" + localDateTime.getMinute() + ":" + localDateTime.getSecond(); - } - - case HOUR: { - return String.valueOf(LocalDateTime.now().getHour()); - } - - default: - return ""; - } - } - - public YLogger setTime(Time time) { - this.time = time; - return this; - } - - public YLogger setColored(boolean state) { - this.colored = state; - if (state) { - if (!AnsiConsole.isInstalled()) { - AnsiConsole.systemInstall(); - } - } - return this; - } - - - public YLogger outputToFile(File file, int buffer) { - return outputToFile(new YFile(file), buffer); - } - - public YLogger outputToFile(YFile file, int bufferSize) { - this.file = file; - if (file.file().exists()) - file.delete(); - - this.save = true; - this.bufferSize = bufferSize; - if (buffer == null) { - buffer = new String[bufferSize]; - } - return this; - } - - public YLogger stopOutput() { - flush(); - save = false; - return this; - } - - - public YLogger setBufferSize(int bufferSize) { - this.bufferSize = bufferSize; - if (buffer != null) { - flush(); - } - buffer = new String[bufferSize]; - return this; - } - - public YLogger setPrefix(String value) { - this.prefix = true; - name = "[" + value + "]"; - return this; - } - - public enum Time { - MILLISECONDS, - HOUR_MINUTES, - HOUR_MINUTES_SECONDS, - HOUR, - NO_TIME - } -} diff --git a/src/pisi/unitedmeows/yystal/networking/IPAddress.java b/src/pisi/unitedmeows/yystal/networking/IPAddress.java deleted file mode 100644 index e36c8b8..0000000 --- a/src/pisi/unitedmeows/yystal/networking/IPAddress.java +++ /dev/null @@ -1,54 +0,0 @@ -package pisi.unitedmeows.yystal.networking; - - -import pisi.unitedmeows.yystal.clazz.prop; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -public class IPAddress { - - public static final IPAddress LOOPBACK = new IPAddress("127.0.0.1"); - public static final IPAddress ANY = new IPAddress("0.0.0.0"); - - private final String address; - public prop inetAddress = new prop(null) { - @Override - public InetAddress get() { - if (value == null) { - try { - value = InetAddress.getByName(getAddress()); - } catch (UnknownHostException e) { - - } - } - return value; - } - - @Deprecated - @Override - public void set(InetAddress newValue) {} - }; - - - protected IPAddress(String _address) { - address = _address; - } - - public static IPAddress from(String address) { - return new IPAddress(address); - } - - public static IPAddress parse(String address) { - try { - return new IPAddress(InetAddress.getByName(address).getHostAddress()); - } catch (UnknownHostException e) { - return null; - } - } - - public String getAddress() { - return address; - } - -} diff --git a/src/pisi/unitedmeows/yystal/networking/basic/YTcpEchoServer.java b/src/pisi/unitedmeows/yystal/networking/basic/YTcpEchoServer.java deleted file mode 100644 index 7305bc6..0000000 --- a/src/pisi/unitedmeows/yystal/networking/basic/YTcpEchoServer.java +++ /dev/null @@ -1,75 +0,0 @@ -package pisi.unitedmeows.yystal.networking.basic; - -import pisi.unitedmeows.yystal.YYStal; -import pisi.unitedmeows.yystal.clazz.event; -import pisi.unitedmeows.yystal.clazz.ref; -import pisi.unitedmeows.yystal.networking.IPAddress; -import pisi.unitedmeows.yystal.networking.events.SDataReceivedEvent; -import pisi.unitedmeows.yystal.networking.events.SEchoEvent; -import pisi.unitedmeows.yystal.networking.server.YSocketClient; -import pisi.unitedmeows.yystal.networking.server.YTcpServer; - -import java.io.UnsupportedEncodingException; -import java.util.regex.Pattern; - -/* simply echo's the string data to client */ -public class YTcpEchoServer { - - protected YTcpServer tcpServer; - - public event echoEvent = new event<>(); - - public YTcpEchoServer(IPAddress bindAddress, int port) { - tcpServer = new YTcpServer(bindAddress, port); - tcpServer.dataReceiveEvent.bind(new SDataReceivedEvent() { - @Override - public void onClientDataReceived(YSocketClient client, byte[] data) { - System.out.println(new String(data) + " < RECEIVED"); - if (data.length < 8192) { - ref canceled = YYStal.reference(false); - echoEvent.fire(client, data, canceled); - if (!canceled.get()) { - client.write(data); - } - } - } - }); - - } - - public void close() { - tcpServer.close(); - } - - public boolean listen() { - return tcpServer.listen(); - } - - public YTcpServer tcpServer() { - return tcpServer; - } - - /* maybe put this in a util class */ - protected static boolean looksLikeUTF8(byte[] utf8) - { - Pattern p = Pattern.compile("\\A(\n" + - " [\\x09\\x0A\\x0D\\x20-\\x7E] # ASCII\\n" + - "| [\\xC2-\\xDF][\\x80-\\xBF] # non-overlong 2-byte\n" + - "| \\xE0[\\xA0-\\xBF][\\x80-\\xBF] # excluding overlongs\n" + - "| [\\xE1-\\xEC\\xEE\\xEF][\\x80-\\xBF]{2} # straight 3-byte\n" + - "| \\xED[\\x80-\\x9F][\\x80-\\xBF] # excluding surrogates\n" + - "| \\xF0[\\x90-\\xBF][\\x80-\\xBF]{2} # planes 1-3\n" + - "| [\\xF1-\\xF3][\\x80-\\xBF]{3} # planes 4-15\n" + - "| \\xF4[\\x80-\\x8F][\\x80-\\xBF]{2} # plane 16\n" + - ")*\\z", Pattern.COMMENTS); - - String phonyString = null; - try { - phonyString = new String(utf8, "ISO-8859-1"); - } catch(UnsupportedEncodingException e) { - return false; - } - return p.matcher(phonyString).matches(); - } - -} diff --git a/src/pisi/unitedmeows/yystal/networking/client/YTcpClient.java b/src/pisi/unitedmeows/yystal/networking/client/YTcpClient.java deleted file mode 100644 index faae2bc..0000000 --- a/src/pisi/unitedmeows/yystal/networking/client/YTcpClient.java +++ /dev/null @@ -1,250 +0,0 @@ -package pisi.unitedmeows.yystal.networking.client; - -import pisi.unitedmeows.yystal.YSettings; -import pisi.unitedmeows.yystal.YYStal; -import pisi.unitedmeows.yystal.clazz.event; -import pisi.unitedmeows.yystal.clazz.mutex; -import pisi.unitedmeows.yystal.clazz.out; -import pisi.unitedmeows.yystal.clazz.ref; -import pisi.unitedmeows.yystal.exception.YExManager; -import pisi.unitedmeows.yystal.exception.impl.YexIO; -import pisi.unitedmeows.yystal.networking.IPAddress; -import pisi.unitedmeows.yystal.networking.client.extension.CTcpExtension; -import pisi.unitedmeows.yystal.networking.client.extension.impl.CTcpFixedSize; -import pisi.unitedmeows.yystal.networking.events.CDataReceivedEvent; -import pisi.unitedmeows.yystal.utils.kThread; - -import java.io.*; -import java.net.Socket; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; - -public class YTcpClient { - - /* receives the data the server has sent */ - protected Thread receiveThread; - /* writes the data that in the queue */ - protected Thread writeThread; - - /* send queue */ - protected Queue _sendQueue; - - /* raw java socket */ - protected Socket socket; - - /* connected server address */ - protected IPAddress connectedAddress; - - /* connected server port */ - protected int connectedPort; - - protected DataInputStream inputStream; - protected DataOutputStream outputStream; - - private byte[] BUFFER = new byte[4096 * 2]; - protected List extensions; - - - public event dataReceivedEvent; - - public YTcpClient() { - _sendQueue = new ConcurrentLinkedQueue<>(); - extensions = new ArrayList<>(); - dataReceivedEvent = new event<>(); - } - - /* connects to client */ - public boolean connect(IPAddress address, int port) { - - final ref connectionAddress = YYStal.reference(address); - final ref connectionPort = YYStal.reference(port); - final ref accepted = YYStal.reference(true); - - // applying the extensions - extensions().forEach(x-> { - x.onConnection(connectionAddress, connectionPort, accepted); - }); - - - if (!accepted.get()) { - return false; - } - - address = connectionAddress.get(); - port = connectionPort.get(); - - if (socket != null && socket.isConnected()) { - try { - /* maybe don't stop?? */ - socket.close(); - receiveThread.stop(); - writeThread.stop(); - } catch (IOException e) { - - } - } - try { - socket = new Socket(address.getAddress(), port); - } catch (IOException e) { - YExManager.pop(new YexIO(String.format("Couldn't connect to server %s with port of %d " + System.lineSeparator() + " Raw Exception: %s", address.getAddress(), port, e.getMessage()))); - return false; - } - try { - socket.setReuseAddress(true); - socket.setTcpNoDelay(true); - - outputStream = new DataOutputStream(socket.getOutputStream()); - inputStream = new DataInputStream(socket.getInputStream()); - } catch (IOException ex) { - YExManager.pop(new YexIO("Couldn't change socket attributes")); - } - - - - - if (socket.isConnected()) { - receiveThread = new Thread(this::read); - receiveThread.start(); - - writeThread = new Thread(this::write); - writeThread.start(); - - connectedAddress = address; - connectedPort = port; - return true; - } else { - return false; - } - } - - protected void write() { - while (isConnected()) { - if (_sendQueue.isEmpty()) { - kThread.sleep(YYStal.setting(YSettings.TCP_CLIENT_QUEUE_CHECK_DELAY)); - } else { - byte[] data = _sendQueue.poll(); - try { - ref modifiedData = YYStal.reference(data); - ref shouldSend = YYStal.reference(true); - - extensions().forEach(extension -> { - extension.onDataSend(modifiedData, shouldSend); - }); - - if (shouldSend.get()) { - outputStream.write(modifiedData.get()); - outputStream.flush(); - } - } catch (IOException e) { - YExManager.pop(new YexIO(String.format("Unable to send data to server %s", e.getMessage()))); - } - - kThread.sleep(YYStal.setting(YSettings.TCP_CLIENT_WRITE_DELAY)); - } - } - } - - public YTcpClient makeFixed() { - extensions().add(new CTcpFixedSize()); - return this; - } - - - public void send(byte[] data) { - _sendQueue.add(data); - } - - public void close() { - if (socket != null && socket.isConnected()) { - ref canceled = YYStal.reference(false); - extensions().forEach(extension -> { - extension.onSocketClose(canceled); - }); - extensions.clear(); - if (!canceled.get()) { - _close(); - } - } - } - - public byte[] readNext() { - ref receivedData = YYStal.reference(null); - final mutex waitLock = new mutex(); - - int delegateId = dataReceivedEvent.bind(new CDataReceivedEvent() { - @Override - public void onDataReceived(byte[] data) { - receivedData.set(data); - waitLock.unlock(); - } - }); - waitLock.lock(); - dataReceivedEvent.free(delegateId); - return receivedData.get(); - } - - private boolean _close() { - try { - socket.close(); - receiveThread.stop(); - writeThread.stop(); - return true; - } catch (Exception ex) { - return false; - } - } - - - protected void read() { - while (isConnected()) { - try { - ref cancelDefaultReader = YYStal.reference(false); - out readData = YYStal.out(); - extensions.forEach(x -> { - x.onPreDataReceive(inputStream, cancelDefaultReader, readData); - }); - - if (cancelDefaultReader.get()) { - dataReceivedEvent.fire((Object) readData.get()); - ref modifiedData = YYStal.reference(readData.get()); - extensions.forEach(x -> { - x.onPostDataReceive(modifiedData); - }); - } else { - int size = inputStream.read(BUFFER); - if (size < 0) { - close(); - return; - } - byte[] data = Arrays.copyOf(BUFFER, size); - ref modifiedData = YYStal.reference(data); - extensions.forEach(x -> { - x.onPostDataReceive(modifiedData); - }); - dataReceivedEvent.fire((Object) modifiedData.get()); - } - } catch (IOException ex) { - YExManager.pop(new YexIO(String.format("Unable to receive data from the server %s", ex.getMessage()))); - } - } - } - - public List extensions() { - return extensions; - } - - public Socket socket() { return socket; } - - public void registerExtension(CTcpExtension extension) { - extension.setup(this); - extensions().add(extension); - } - - public boolean isConnected() { - return socket != null && !socket.isClosed() && socket.isConnected(); - } - -} diff --git a/src/pisi/unitedmeows/yystal/networking/client/YUdpClient.java b/src/pisi/unitedmeows/yystal/networking/client/YUdpClient.java deleted file mode 100644 index 023242f..0000000 --- a/src/pisi/unitedmeows/yystal/networking/client/YUdpClient.java +++ /dev/null @@ -1,90 +0,0 @@ -package pisi.unitedmeows.yystal.networking.client; - -import pisi.unitedmeows.yystal.clazz.event; -import pisi.unitedmeows.yystal.exception.YExManager; -import pisi.unitedmeows.yystal.exception.impl.YexIO; -import pisi.unitedmeows.yystal.networking.IPAddress; -import pisi.unitedmeows.yystal.networking.events.CUdpDataReceived; - -import java.io.Closeable; -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.util.Arrays; - -public class YUdpClient implements Closeable { - - protected IPAddress connectedHost; - protected int connectedPort; - protected DatagramSocket socket; - private Thread receiveThread; - private byte[] buffer; - - public event onDataReceived = new event(); - - public YUdpClient() { - this(512); - } - - public YUdpClient(int bufferSize) { - buffer = new byte[bufferSize]; - } - - public boolean connect(IPAddress _address, int _port) { - if (socket != null) { - socket.close(); - } - try { - socket = new DatagramSocket(); - } catch (Exception ex) { - YExManager.pop(new YexIO(String.format("Couldn't connect to the udp server %s", ex.getMessage()))); - return false; - } - - connectedHost = _address; - connectedPort = _port; - - if (receiveThread != null) { - try { - receiveThread.stop(); - } catch (Exception ex) { - YExManager.pop(new YexIO(String.format("Couldn't stop last receive thread %s", ex.getMessage()))); - } - } - - receiveThread = new Thread(this::receive); - receiveThread.start(); - return true; - } - - public void receive() { - while (isConnected()) { - DatagramPacket response = new DatagramPacket(buffer, buffer.length); - try { - socket.receive(response); - byte[] received = Arrays.copyOfRange(buffer, 0, response.getLength()); - onDataReceived.fire(received); - } catch (Exception ex){ - ex.printStackTrace(); - } - } - } - - public void send(byte[] data) { - DatagramPacket request = new DatagramPacket(data, data.length, connectedHost.inetAddress.get(), connectedPort); - try { - socket.send(request); - } catch (IOException ex) { - YExManager.pop(new YexIO(String.format("Couldn't send the data %s", ex.getMessage()))); - } - } - - @Override - public void close() throws IOException { - socket.close(); - } - - public boolean isConnected() { - return !socket.isClosed(); - } -} diff --git a/src/pisi/unitedmeows/yystal/networking/client/extension/CTcpExtension.java b/src/pisi/unitedmeows/yystal/networking/client/extension/CTcpExtension.java deleted file mode 100644 index 75c2fde..0000000 --- a/src/pisi/unitedmeows/yystal/networking/client/extension/CTcpExtension.java +++ /dev/null @@ -1,38 +0,0 @@ -package pisi.unitedmeows.yystal.networking.client.extension; - -import pisi.unitedmeows.yystal.clazz.out; -import pisi.unitedmeows.yystal.clazz.ref; -import pisi.unitedmeows.yystal.networking.IPAddress; -import pisi.unitedmeows.yystal.networking.client.YTcpClient; - -import java.io.DataInputStream; - -public class CTcpExtension { - - protected YTcpClient client; - - public void setup(YTcpClient tcpClient) { - client = tcpClient; - } - - public void onConnection(ref connectionIp, ref connectionPort, ref accepted) { - - } - - public void onPostDataReceive(ref data) { - - } - - public void onPreDataReceive(DataInputStream inputStream, ref cancelDefaultReader, out readData) { - - } - - public void onDataSend(ref data, ref send) { - - } - - public void onSocketClose(ref cancel) { - - } - -} diff --git a/src/pisi/unitedmeows/yystal/networking/client/extension/impl/CTcpFixedSize.java b/src/pisi/unitedmeows/yystal/networking/client/extension/impl/CTcpFixedSize.java deleted file mode 100644 index 58fdcb6..0000000 --- a/src/pisi/unitedmeows/yystal/networking/client/extension/impl/CTcpFixedSize.java +++ /dev/null @@ -1,41 +0,0 @@ -package pisi.unitedmeows.yystal.networking.client.extension.impl; - -import pisi.unitedmeows.yystal.clazz.out; -import pisi.unitedmeows.yystal.clazz.ref; -import pisi.unitedmeows.yystal.networking.client.extension.CTcpExtension; -import pisi.unitedmeows.yystal.utils.MemoryWriter; - -import java.io.DataInputStream; -import java.io.IOException; - -public class CTcpFixedSize extends CTcpExtension { - - @Override - public void onDataSend(ref data, ref send) { - MemoryWriter memoryWriter = new MemoryWriter(); - - try { - memoryWriter.writeInt(data.get().length); - memoryWriter.write(data.get()); - } catch (Exception ex) { - - } - data.set(memoryWriter.getBytes()); - send.set(true); - try { - memoryWriter.close(); - } catch (IOException e) {} - } - - @Override - public void onPreDataReceive(DataInputStream inputStream, ref cancelDefaultReader, out readData) { - try { - int size = inputStream.readInt(); - byte[] received = new byte[size]; - inputStream.read(received); - readData.set(received); - cancelDefaultReader.set(true); - } catch (Exception ex) { - } - } -} diff --git a/src/pisi/unitedmeows/yystal/networking/client/extension/impl/CTcpLineRead.java b/src/pisi/unitedmeows/yystal/networking/client/extension/impl/CTcpLineRead.java deleted file mode 100644 index 90887f6..0000000 --- a/src/pisi/unitedmeows/yystal/networking/client/extension/impl/CTcpLineRead.java +++ /dev/null @@ -1,42 +0,0 @@ -package pisi.unitedmeows.yystal.networking.client.extension.impl; - -import pisi.unitedmeows.yystal.clazz.out; -import pisi.unitedmeows.yystal.clazz.ref; -import pisi.unitedmeows.yystal.networking.client.YTcpClient; -import pisi.unitedmeows.yystal.networking.client.extension.CTcpExtension; - -import java.io.BufferedReader; -import java.io.DataInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; - -public class CTcpLineRead extends CTcpExtension { - - protected YTcpClient client; - protected BufferedReader bufferedReader; - - @Override - public void setup(YTcpClient tcpClient) { - client = tcpClient; - } - - @Override - public void onPreDataReceive(DataInputStream inputStream, ref cancelDefaultReader, out readData) { - if (bufferedReader == null) { - bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); - } - - try { - String readLine = bufferedReader.readLine(); - if (readLine == null) { - client.close(); - cancelDefaultReader.set(true); - readData.set(null); - return; - } - cancelDefaultReader.set(true); - readData.set(readLine.getBytes(StandardCharsets.UTF_8)); - } catch (Exception ex) {} - } -} diff --git a/src/pisi/unitedmeows/yystal/networking/events/CDataReceivedEvent.java b/src/pisi/unitedmeows/yystal/networking/events/CDataReceivedEvent.java deleted file mode 100644 index 99b4579..0000000 --- a/src/pisi/unitedmeows/yystal/networking/events/CDataReceivedEvent.java +++ /dev/null @@ -1,8 +0,0 @@ -package pisi.unitedmeows.yystal.networking.events; - -import pisi.unitedmeows.yystal.clazz.delegate; - -@FunctionalInterface -public interface CDataReceivedEvent extends delegate { - public void onDataReceived(byte[] data); -} diff --git a/src/pisi/unitedmeows/yystal/networking/events/CUdpDataReceived.java b/src/pisi/unitedmeows/yystal/networking/events/CUdpDataReceived.java deleted file mode 100644 index 5f0bbae..0000000 --- a/src/pisi/unitedmeows/yystal/networking/events/CUdpDataReceived.java +++ /dev/null @@ -1,7 +0,0 @@ -package pisi.unitedmeows.yystal.networking.events; - -import pisi.unitedmeows.yystal.clazz.delegate; - -public interface CUdpDataReceived extends delegate { - public void onDataReceived(byte[] data); -} diff --git a/src/pisi/unitedmeows/yystal/networking/events/SConnectionReceivedEvent.java b/src/pisi/unitedmeows/yystal/networking/events/SConnectionReceivedEvent.java deleted file mode 100644 index 0c74abf..0000000 --- a/src/pisi/unitedmeows/yystal/networking/events/SConnectionReceivedEvent.java +++ /dev/null @@ -1,8 +0,0 @@ -package pisi.unitedmeows.yystal.networking.events; - -import pisi.unitedmeows.yystal.clazz.delegate; -import pisi.unitedmeows.yystal.networking.server.YSocketClient; - -public interface SConnectionReceivedEvent extends delegate { - public void onClientConnected(YSocketClient socketClient); -} diff --git a/src/pisi/unitedmeows/yystal/networking/events/SDataReceivedEvent.java b/src/pisi/unitedmeows/yystal/networking/events/SDataReceivedEvent.java deleted file mode 100644 index 73374b4..0000000 --- a/src/pisi/unitedmeows/yystal/networking/events/SDataReceivedEvent.java +++ /dev/null @@ -1,8 +0,0 @@ -package pisi.unitedmeows.yystal.networking.events; - -import pisi.unitedmeows.yystal.clazz.delegate; -import pisi.unitedmeows.yystal.networking.server.YSocketClient; - -public interface SDataReceivedEvent extends delegate { - public void onClientDataReceived(YSocketClient client, byte[] data); -} diff --git a/src/pisi/unitedmeows/yystal/networking/events/SEchoEvent.java b/src/pisi/unitedmeows/yystal/networking/events/SEchoEvent.java deleted file mode 100644 index 52bc6be..0000000 --- a/src/pisi/unitedmeows/yystal/networking/events/SEchoEvent.java +++ /dev/null @@ -1,9 +0,0 @@ -package pisi.unitedmeows.yystal.networking.events; - -import pisi.unitedmeows.yystal.clazz.delegate; -import pisi.unitedmeows.yystal.clazz.ref; -import pisi.unitedmeows.yystal.networking.server.YSocketClient; - -public interface SEchoEvent extends delegate { - public void onDataReceived(YSocketClient socketClient, byte[] data, ref canceled); -} diff --git a/src/pisi/unitedmeows/yystal/networking/server/YSocketClient.java b/src/pisi/unitedmeows/yystal/networking/server/YSocketClient.java deleted file mode 100644 index de108f0..0000000 --- a/src/pisi/unitedmeows/yystal/networking/server/YSocketClient.java +++ /dev/null @@ -1,135 +0,0 @@ -package pisi.unitedmeows.yystal.networking.server; - -import pisi.unitedmeows.yystal.YYStal; -import pisi.unitedmeows.yystal.clazz.out; -import pisi.unitedmeows.yystal.clazz.ref; -import pisi.unitedmeows.yystal.exception.YExManager; -import pisi.unitedmeows.yystal.exception.impl.YexIO; -import pisi.unitedmeows.yystal.networking.server.extension.STcpExtension; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.net.Socket; -import java.util.Arrays; -import java.util.Iterator; - -public class YSocketClient { - - private static byte[] BUFFER = new byte[4096 * 2]; - private final Socket socket; - private YTcpServer connectedServer; - private Thread receiveThread; - - private DataInputStream inputStream; - private DataOutputStream outputStream; - - public YSocketClient(Socket _socket, YTcpServer _connectedServer) { - socket = _socket; - connectedServer = _connectedServer; - - try { - inputStream = new DataInputStream(socket.getInputStream()); - outputStream = new DataOutputStream(socket.getOutputStream()); - socket.setTcpNoDelay(true); - socket.setReuseAddress(true); - } catch (IOException ex) { - YExManager.pop(new YexIO(String.format("Couldn't set attributes of connected client %s", ex.getMessage()))); - } - receiveThread = new Thread(this::receive); - receiveThread.start(); - } - - public void write(byte[] data) { - if (isDisconnected()) { - return; - } - try { - ref sendData = YYStal.reference(data); - ref shouldSend = YYStal.reference(true); - connectedServer().extensions().forEach(x-> { - x.onDataSend(this, sendData, shouldSend); - }); - if (shouldSend.get()) { - outputStream.write(sendData.get()); - outputStream.flush(); - } - } catch (IOException ex) { - YExManager.pop(new YexIO(String.format("Couldn't send data to client %s", ex.getMessage()))); - } - } - - public void _preClose() { - try { - socket.close(); - outputStream.close(); - inputStream.close(); - connectedServer = null; - } catch (Exception ex) { - - } - } - - public void close() { - try { - socket.close(); - outputStream.close(); - inputStream.close(); - Iterator socketClientIterator = connectedServer().connectedClients().iterator(); - while (socketClientIterator.hasNext()) { - if (socketClientIterator.next() == this) { - socketClientIterator.remove(); - break; - } - } - connectedServer().extensions().forEach(x -> { - x.onClientDisconnect(this); - }); - - } catch (IOException ex) { - YExManager.pop(new YexIO(String.format("Error while closing the client's socket %s", ex.getMessage()))); - } - } - - public YTcpServer connectedServer() { - return connectedServer; - } - - public boolean isDisconnected() { - return socket == null || !socket.isConnected() || socket.isClosed(); - } - - protected void receive() { - while (socket.isConnected() && !socket.isClosed()) { - try { - ref cancelDefaultReader = YYStal.reference(false); - out receiveData = YYStal.out(); - connectedServer().extensions().forEach(extension -> { - extension.onPreDataReceive(this, inputStream, cancelDefaultReader, receiveData); - }); - byte[] data; - if (cancelDefaultReader.get()) { - data = receiveData.get(); - } else { - int size = inputStream.read(BUFFER); - if (size >= 0) - data = Arrays.copyOf(BUFFER, size); - else { - data = new byte[0]; - close(); - } - } - - connectedServer().dataReceiveEvent.fire(this, data); - ref refData = YYStal.reference(data); - connectedServer().extensions().forEach(extension -> { - extension.onPostDataReceive(this, refData); - }); - - } catch (IOException ex) { - YExManager.pop(new YexIO(String.format("Couldn't receive data from the client %s", ex.getMessage()))); - } - } - } - -} \ No newline at end of file diff --git a/src/pisi/unitedmeows/yystal/networking/server/YTcpServer.java b/src/pisi/unitedmeows/yystal/networking/server/YTcpServer.java deleted file mode 100644 index 1683bae..0000000 --- a/src/pisi/unitedmeows/yystal/networking/server/YTcpServer.java +++ /dev/null @@ -1,127 +0,0 @@ -package pisi.unitedmeows.yystal.networking.server; - -import pisi.unitedmeows.yystal.YYStal; -import pisi.unitedmeows.yystal.clazz.event; -import pisi.unitedmeows.yystal.clazz.ref; -import pisi.unitedmeows.yystal.exception.YExManager; -import pisi.unitedmeows.yystal.exception.impl.YexIO; -import pisi.unitedmeows.yystal.networking.IPAddress; -import pisi.unitedmeows.yystal.networking.events.SConnectionReceivedEvent; -import pisi.unitedmeows.yystal.networking.events.SDataReceivedEvent; -import pisi.unitedmeows.yystal.networking.server.extension.STcpExtension; -import pisi.unitedmeows.yystal.networking.server.extension.impl.STcpFixedSize; - -import java.io.IOException; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -public class YTcpServer { - - /* listening ip address */ - private IPAddress listening; - - /* listening port */ - private int port; - - /* connected clients */ - private List connectedClients; - - /* data receive event */ - public event dataReceiveEvent = new event<>(); - public event connectionReceivedEvent = new event<>(); - - private Thread connectionThread; - private ServerSocket serverSocket; - private List extensions; - - - public YTcpServer(IPAddress _listenIp, int _listenPort) { - listening = _listenIp; - port = _listenPort; - extensions = new ArrayList<>(); - } - - public YTcpServer(ServerSocket _serverSocket, IPAddress _listenIp, int _listenPort) { - this(_listenIp, _listenPort); - serverSocket = _serverSocket; - } - - public void registerExtension(STcpExtension extension) { - extensions().add(extension); - extension.setup(this); - } - - - public boolean listen() { - if (serverSocket == null) { - try { - serverSocket = new ServerSocket(port, 50, listening.inetAddress.get()); - } catch (IOException e) { - YExManager.pop(new YexIO(String.format("Couldn't start the server %s", e.getMessage()))); - return false; - } - } - connectedClients = new ArrayList<>(); - connectionThread = new Thread(this::startListening); - connectionThread.start(); - return true; - } - - private void startListening() { - while (!serverSocket.isClosed()) { - try { - Socket socket = serverSocket.accept(); - ref accepted = YYStal.reference(true); - extensions.forEach(x-> { - x.onConnectionRequest(socket, accepted); - }); - - if (accepted.get()) { - YSocketClient ySocketClient = new YSocketClient(socket, this); - connectedClients.add(ySocketClient); - connectionReceivedEvent.fire(ySocketClient); - } else { - socket.close(); - } - } catch (IOException ex) { - YExManager.pop(new YexIO(String.format("Server couldn't accept the client %s", ex.getMessage()))); - } - } - } - - public void close() { - try { - kickAll(); - connectedClients.clear(); - serverSocket.close(); - } catch(IOException e) { - - } - } - - public void kickAll() { - for (YSocketClient client : connectedClients()) { - client._preClose(); - } - } - - public YTcpServer makeFixed() { - extensions().add(new STcpFixedSize()); - return this; - } - - public List extensions() { - return extensions; - } - - public List connectedClients() { - return connectedClients; - } - - public int port() { - return port; - } -} diff --git a/src/pisi/unitedmeows/yystal/networking/server/extension/STcpExtension.java b/src/pisi/unitedmeows/yystal/networking/server/extension/STcpExtension.java deleted file mode 100644 index 0b5b648..0000000 --- a/src/pisi/unitedmeows/yystal/networking/server/extension/STcpExtension.java +++ /dev/null @@ -1,38 +0,0 @@ -package pisi.unitedmeows.yystal.networking.server.extension; - -import pisi.unitedmeows.yystal.clazz.out; -import pisi.unitedmeows.yystal.clazz.ref; -import pisi.unitedmeows.yystal.networking.server.YSocketClient; -import pisi.unitedmeows.yystal.networking.server.YTcpServer; - -import java.io.DataInputStream; -import java.net.Socket; - -public class STcpExtension { - protected YTcpServer server; - - public void setup(YTcpServer _server) { - server = _server; - } - - public void onConnectionRequest(Socket socket, ref accepted) { - - } - - public void onClientDisconnect(YSocketClient client) { - - } - - public void onPostDataReceive(YSocketClient client, ref data) { - - } - - public void onPreDataReceive(YSocketClient client, DataInputStream inputStream, ref cancelDefaultReader, out readData) { - - } - - public void onDataSend(YSocketClient client, ref data, ref send) { - - } - -} diff --git a/src/pisi/unitedmeows/yystal/networking/server/extension/impl/STcpFixedSize.java b/src/pisi/unitedmeows/yystal/networking/server/extension/impl/STcpFixedSize.java deleted file mode 100644 index 4077afc..0000000 --- a/src/pisi/unitedmeows/yystal/networking/server/extension/impl/STcpFixedSize.java +++ /dev/null @@ -1,45 +0,0 @@ -package pisi.unitedmeows.yystal.networking.server.extension.impl; - -import pisi.unitedmeows.yystal.clazz.out; -import pisi.unitedmeows.yystal.clazz.ref; -import pisi.unitedmeows.yystal.networking.server.YSocketClient; -import pisi.unitedmeows.yystal.networking.server.extension.STcpExtension; -import pisi.unitedmeows.yystal.utils.MemoryWriter; - -import java.io.DataInputStream; -import java.io.IOException; - -public class STcpFixedSize extends STcpExtension { - - @Override - public void onPreDataReceive(YSocketClient client, DataInputStream inputStream, ref cancelDefaultReader, out readData) { - try { - int dataSize = inputStream.readInt(); - if (dataSize > 65535) { - dataSize = 65535; - } - byte[] data = new byte[dataSize]; - inputStream.read(data); - cancelDefaultReader.set(true); - readData.set(data); - - } catch (Exception ex) { - } - } - - @Override - public void onDataSend(YSocketClient client, ref data, ref send) { - try { - byte[] rawData = data.get(); - MemoryWriter memoryWriter = new MemoryWriter(); - memoryWriter.writeInt(rawData.length); - memoryWriter.write(rawData); - data.set(memoryWriter.getBytes()); - send.set(true); - try { - memoryWriter.close(); - } catch (IOException e) {} - } catch (Exception ex) { - } - } -} diff --git a/src/pisi/unitedmeows/yystal/networking/server/extension/impl/STcpLineRead.java b/src/pisi/unitedmeows/yystal/networking/server/extension/impl/STcpLineRead.java deleted file mode 100644 index 0144a20..0000000 --- a/src/pisi/unitedmeows/yystal/networking/server/extension/impl/STcpLineRead.java +++ /dev/null @@ -1,43 +0,0 @@ -package pisi.unitedmeows.yystal.networking.server.extension.impl; - -import pisi.unitedmeows.yystal.clazz.out; -import pisi.unitedmeows.yystal.clazz.ref; -import pisi.unitedmeows.yystal.clazz.soulbound; -import pisi.unitedmeows.yystal.networking.server.YSocketClient; -import pisi.unitedmeows.yystal.networking.server.extension.STcpExtension; - -import java.io.BufferedReader; -import java.io.DataInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; - -public class STcpLineRead extends STcpExtension { - - private soulbound bufferedBound; - - public STcpLineRead() { - bufferedBound = new soulbound(10000) { - @Override - public boolean breakBound(YSocketClient instance, BufferedReader value) { - return instance.isDisconnected(); - } - - @Override - public void onRemove(YSocketClient instance, BufferedReader value) { - try { value.close(); } catch (IOException e) {} - } - }; - } - - @Override - public void onPreDataReceive(YSocketClient client, DataInputStream inputStream, ref cancelDefaultReader, out readData) { - try { - String read = bufferedBound.computeIfAbsent(client, i -> new BufferedReader(new InputStreamReader(inputStream))).readLine(); - readData.set(read.getBytes(StandardCharsets.UTF_8)); - cancelDefaultReader.set(true); - } catch (Exception e) { - - } - } -} diff --git a/src/pisi/unitedmeows/yystal/parallel/Async.java b/src/pisi/unitedmeows/yystal/parallel/Async.java deleted file mode 100644 index d21ec64..0000000 --- a/src/pisi/unitedmeows/yystal/parallel/Async.java +++ /dev/null @@ -1,317 +0,0 @@ -package pisi.unitedmeows.yystal.parallel; - -import pisi.unitedmeows.yystal.YSettings; -import pisi.unitedmeows.yystal.YYStal; -import pisi.unitedmeows.yystal.clazz.prop; -import pisi.unitedmeows.yystal.utils.kThread; - -public class Async { - - /* runs the function on taskpool without returning a value */ - public static Future async(IFunction function) { - Future future = new Future<>(); - YYStal.taskPool().run(function, future); - return future; - } - - /* runs the function on task pool without returning a value */ - public static void async(Runnable function) { - YYStal.taskPool().run(new IFunction() { - @Override - public Integer run() { - function.run(); - return 1; - } - }, null); - } - - /* runs the task async and if the timeout has reached stops the task and returns the default value */ - public static Future async(IFunction function, long timeout, IFunction defaultValue) { - final Future future = new Future<>(); - Task task = YYStal.taskPool().run(new IFunction() { - @Override - public X run() { - return function.run(); - } - }, future); - - async_w(() -> { - if (!task.isExecuted()) { - future.setResult(defaultValue.run()); - TaskWorker taskWorker = YYStal.taskPool().getWorker(task); - if (taskWorker != null) { - YYStal.taskPool().stopWorker(taskWorker, true); - YYStal.taskPool().newWorker(); - } - } - }, timeout); - return future; - } - - /* runs the task async and if the timeout has reached stops the task and returns the default value */ - public static void async(Runnable runnable, long timeout) { - Task task = YYStal.taskPool().run(new IFunction() { - @Override - public Integer run() { - runnable.run(); - return 1; - } - }, null); - - async_w(() -> { - if (!task.isExecuted()) { - TaskWorker taskWorker = YYStal.taskPool().getWorker(task); - if (taskWorker != null) { - YYStal.taskPool().stopWorker(taskWorker, true); - YYStal.taskPool().newWorker(); - } - } - }, timeout); - } - - - // runs the function on the new thread and returns the future - // this method does not use thread pool - public static Future async_t(IFunction function) { - Future future = new Future<>(); - new Thread(new Runnable() { - @Override - public void run() { - future.setResult(function.run()); - } - }).start(); - return future; - } - - // runs the function on the new thread - // this method does not use thread pool - public static void async_t(Runnable runnable) { - new Thread(runnable).start(); - } - - /* runs the function on the taskpool but with a delay */ - public static Future async_w(IFunction function, long after) { - Future future = new Future<>(); - YYStal.taskPool().run_w(function, future, after); - return (Future) future; - } - - /* runs the function on the taskpool but with a delay */ - public static void async_w(Runnable function, long after) { - YYStal.taskPool().run_w(new IFunction() { - @Override - public Integer run() { - function.run(); - return 1; - } - }, null, after); - } - - /* - runs the function on the taskpool async and blocks the running thread - till the function has executed and returns the value - */ - public static X await(IFunction function) { - Future future = new Future<>(); - Task task = YYStal.taskPool().run(function, future); - while (!task.isExecuted()) { - kThread.sleep(YYStal.setting(YSettings.TASK_AWAIT_DELAY)); - } - return future.result(); - } - - - // runs the function on new thread and locks the current thread then returns the value - public static X await_t(IFunction function) { - prop prop = new prop<>(); - prop executed = new prop<>(false); - new Thread(new Runnable() { - @Override - public void run() { - prop.set(function.run()); - executed.set(true); - } - }).start(); - while (!executed.get()) { - kThread.sleep(YYStal.setting(YSettings.TASK_AWAIT_DELAY)); - } - return prop.get(); - } - // runs the function on new thread and locks the current thread till it finished - public static void await_t(Runnable runnable) { - prop executed = new prop<>(false); - new Thread(new Runnable() { - @Override - public void run() { - runnable.run(); - executed.set(true); - } - }).start(); - while (!executed.get()) { - kThread.sleep(YYStal.setting(YSettings.TASK_AWAIT_DELAY)); - } - } - - /* - runs the function on the taskpool async and blocks the running thread - till the function has executed - */ - public static void await(Runnable runnable) { - Task task = YYStal.taskPool().run(new IFunction() { - @Override - public Integer run() { - runnable.run(); - return 1; - } - }, null); - while (!task.isExecuted()) { - kThread.sleep(YYStal.setting(YSettings.TASK_AWAIT_DELAY)); - } - } - - /* runs the function as a loop async */ - public static Promise async_loop(Runnable runnable, long interval) { - final Promise promise = new Promise(); - final prop> functionProp = new prop<>(); - - functionProp.set(new IFunction() { - @Override - public Integer run() { - if (promise.isValid()) { - runnable.run(); - async_w(functionProp.get(), interval); - } - return 1; - } - }); - - async(functionProp.get()); - return promise; - } - - /* runs the function as loop async but starts the loop with a delay same as interval value */ - public static Promise async_loop_w(Runnable runnable, long interval) { - return async_loop_w(runnable, interval, interval); - } - - /* runs the function as loop async but starts the loop with a delay */ - public static Promise async_loop_w(Runnable runnable, long interval, long startAfter) { - final Promise promise = new Promise(); - final prop> functionProp = new prop<>(); - - functionProp.set(new IFunction() { - @Override - public Integer run() { - if (promise.isValid()) { - runnable.run(); - async_w(functionProp.get(), interval); - } - return 1; - } - }); - - async_w(functionProp.get(), startAfter); - return promise; - } - - /* runs the loop async x times */ - public static Promise async_loop_times(Runnable runnable, long interval, int times) { - final Promise promise = new Promise(); - final prop> functionProp = new prop<>(); - final prop counter = new prop<>(times); - functionProp.set(new IFunction() { - @Override - public Integer run() { - if (promise.isValid()) { - runnable.run(); - - counter.set(counter.get() + 1); - if (counter.get() >= times) { - promise.stop(); - return 1; - } - async_w(functionProp.get(), interval); - } - return 1; - } - }); - - async(functionProp.get()); - return promise; - } - - /* runs the loop async x times with a startup delay (the interval) */ - public static Promise async_loop_times_w(Runnable runnable, long interval, int times) { - return async_loop_times_w(runnable, interval, times, interval); - } - - /* runs the loop async x times with a startup delay (the after) */ - public static Promise async_loop_times_w(Runnable runnable, long interval, int times, final long startAfter) { - final Promise promise = new Promise(); - final prop> functionProp = new prop<>(); - final prop counter = new prop<>(times); - functionProp.set(new IFunction() { - @Override - public Integer run() { - if (promise.isValid()) { - runnable.run(); - - counter.set(counter.get() + 1); - if (counter.get() >= times) { - promise.stop(); - return 1; - } - async_w(functionProp.get(), interval); - } - return 1; - } - }); - - async_w(functionProp.get(), startAfter); - return promise; - } - - public static Promise async_loop_condition(Runnable runnable, long interval, IState condition) { - final Promise promise = new Promise(); - final prop> functionProp = new prop<>(); - functionProp.set(new IFunction() { - @Override - public Integer run() { - if (promise.isValid() && condition.check()) { - runnable.run(); - - async_w(functionProp.get(), interval); - } - return 1; - } - }); - - async(functionProp.get()); - return promise; - } - - public static Promise async_loop_condition_w(Runnable runnable, long interval, IState condition) { - return async_loop_condition_w(runnable, interval, condition, interval); - } - - public static Promise async_loop_condition_w(Runnable runnable, long interval, IState condition, final long startAfter) { - final Promise promise = new Promise(); - final prop> functionProp = new prop<>(); - functionProp.set(new IFunction() { - @Override - public Integer run() { - if (promise.isValid() && condition.check()) { - runnable.run(); - - async_w(functionProp.get(), interval); - } - return 1; - } - }); - - async_w(functionProp.get(), startAfter); - return promise; - } - - -} diff --git a/src/pisi/unitedmeows/yystal/parallel/Future.java b/src/pisi/unitedmeows/yystal/parallel/Future.java deleted file mode 100644 index 86bd3af..0000000 --- a/src/pisi/unitedmeows/yystal/parallel/Future.java +++ /dev/null @@ -1,23 +0,0 @@ -package pisi.unitedmeows.yystal.parallel; - -public class Future { - - private X result; - private boolean set; - - public void setResult(Object result) { - this.result = (X) result; - set = true; - } - - public boolean hasSet() { - return set; - } - - public X result() { - return result; - } - public Object resultRaw() { - return result; - } -} diff --git a/src/pisi/unitedmeows/yystal/parallel/IFunction.java b/src/pisi/unitedmeows/yystal/parallel/IFunction.java deleted file mode 100644 index bf5a288..0000000 --- a/src/pisi/unitedmeows/yystal/parallel/IFunction.java +++ /dev/null @@ -1,6 +0,0 @@ -package pisi.unitedmeows.yystal.parallel; - -@FunctionalInterface -public interface IFunction { - X run(); -} diff --git a/src/pisi/unitedmeows/yystal/parallel/IState.java b/src/pisi/unitedmeows/yystal/parallel/IState.java deleted file mode 100644 index 180b2d7..0000000 --- a/src/pisi/unitedmeows/yystal/parallel/IState.java +++ /dev/null @@ -1,6 +0,0 @@ -package pisi.unitedmeows.yystal.parallel; - -@FunctionalInterface -public interface IState { - boolean check(); -} diff --git a/src/pisi/unitedmeows/yystal/parallel/ITaskPool.java b/src/pisi/unitedmeows/yystal/parallel/ITaskPool.java deleted file mode 100644 index b721f69..0000000 --- a/src/pisi/unitedmeows/yystal/parallel/ITaskPool.java +++ /dev/null @@ -1,15 +0,0 @@ -package pisi.unitedmeows.yystal.parallel; - -public interface ITaskPool { - Task run(IFunction function, Future future); - Task run_w(IFunction function, Future future, long after); - int workerCount(); - Task nextTask(); - void register(); - void unregister(); - TaskWorker getWorker(); - TaskWorker getWorker(Task task); - void stopWorker(TaskWorker worker); - void stopWorker(TaskWorker worker, boolean abort); - void newWorker(); -} diff --git a/src/pisi/unitedmeows/yystal/parallel/Promise.java b/src/pisi/unitedmeows/yystal/parallel/Promise.java deleted file mode 100644 index c9d36db..0000000 --- a/src/pisi/unitedmeows/yystal/parallel/Promise.java +++ /dev/null @@ -1,18 +0,0 @@ -package pisi.unitedmeows.yystal.parallel; - -public class Promise { - - public Promise() { - valid = true; - } - - private boolean valid; - - public void stop() { - valid = false; - } - - public boolean isValid() { - return valid; - } -} diff --git a/src/pisi/unitedmeows/yystal/parallel/Task.java b/src/pisi/unitedmeows/yystal/parallel/Task.java deleted file mode 100644 index 089b969..0000000 --- a/src/pisi/unitedmeows/yystal/parallel/Task.java +++ /dev/null @@ -1,46 +0,0 @@ -package pisi.unitedmeows.yystal.parallel; - -import pisi.unitedmeows.yystal.utils.Stopwatch; - -public class Task { - - private boolean executed; - private IFunction function; - private long took; - private long startTime; - private Future future; - - public Task(IFunction function, Future future) { - this.function = function; - this.future = future; - } - - public void run() { - startTime = System.currentTimeMillis(); - if (future != null) { - future.setResult(function.run()); - } else { - function.run(); - } - took = System.currentTimeMillis() - startTime; - executed = true; - } - - public boolean isExecuted() { - return executed; - } - - public Future future() { - return future; - } - - public long elapsed() { - return isExecuted() ? took() : System.currentTimeMillis() - startTime; - } - - public long took() { - return took; - } - - -} diff --git a/src/pisi/unitedmeows/yystal/parallel/TaskWorker.java b/src/pisi/unitedmeows/yystal/parallel/TaskWorker.java deleted file mode 100644 index 2dc92f4..0000000 --- a/src/pisi/unitedmeows/yystal/parallel/TaskWorker.java +++ /dev/null @@ -1,66 +0,0 @@ -package pisi.unitedmeows.yystal.parallel; - -import pisi.unitedmeows.yystal.YSettings; -import pisi.unitedmeows.yystal.YYStal; -import pisi.unitedmeows.yystal.utils.Stopwatch; -import pisi.unitedmeows.yystal.utils.kThread; - -public class TaskWorker extends Thread { - - private boolean busy; - private Stopwatch stopwatch; - private long elapsed; - private long lastFinish; - private Task currentTask; - private boolean running; - - public TaskWorker() { - stopwatch = new Stopwatch(); - } - - @Override - public void run() { - running = true; - while (isRunning() && YYStal.mainThread().isAlive()) { - currentTask = YYStal.taskPool().nextTask(); - if (currentTask != null) { - busy = true; - stopwatch.reset(); - currentTask.run(); - elapsed = stopwatch.elapsed(); - lastFinish = System.currentTimeMillis(); - busy = false; - } - kThread.sleep(YYStal.setting(YSettings.TASKWORKER_FETCH_DELAY)); - } - } - - /* stops the worker */ - public void stopWorker() { - running = false; - } - - public void abortWorker() { - stopWorker(); - try { - this.stop(); - } catch (Exception ex) {} - } - - public Task currentTask() { - return currentTask; - } - - public long lastTaskFinish() { - return elapsed; - } - - public boolean isRunning() { - return running; - } - - public boolean isBusy() { - return busy; - } - public long busyTime() { return isBusy() ? stopwatch.elapsed() : 0; } -} diff --git a/src/pisi/unitedmeows/yystal/parallel/pools/BasicTaskPool.java b/src/pisi/unitedmeows/yystal/parallel/pools/BasicTaskPool.java deleted file mode 100644 index 314e097..0000000 --- a/src/pisi/unitedmeows/yystal/parallel/pools/BasicTaskPool.java +++ /dev/null @@ -1,200 +0,0 @@ -package pisi.unitedmeows.yystal.parallel.pools; - -import pisi.unitedmeows.yystal.*; -import pisi.unitedmeows.yystal.parallel.*; -import pisi.unitedmeows.yystal.utils.kThread; - -import java.util.*; -import java.util.concurrent.ConcurrentLinkedQueue; - -public class BasicTaskPool implements ITaskPool -{ - /* taskworkers that runs the tasks */ - private List taskWorkers; - - /* controller thread that controls worker */ - private Thread controlThread; - - /* maximum and the minimum number of workers in a pool */ - private int minWorkers, maxWorkers; - - /* tasks in the queue */ - private ConcurrentLinkedQueue taskQueue; - - private HashMap waitingTasks = new HashMap<>(); - - public BasicTaskPool(int minWorkers, int maxWorkers) { - this.minWorkers = minWorkers; - this.maxWorkers = maxWorkers; - taskWorkers = new ArrayList<>(); - waitingTasks = new HashMap<>(); - taskQueue = new ConcurrentLinkedQueue(); - } - - /* gets called when the client starts using this pool */ - @Override - public void register() { - controlThread = new Thread(new Runnable() { - @Override - public void run() { - control(); - } - }); - - for (int i = 0; i < minWorkers; i++) { - final TaskWorker taskWorker = new TaskWorker(); - taskWorkers.add(taskWorker); - taskWorker.start(); - } - - controlThread.start(); - } - - /* gets called when client switches the pool for another pool */ - @Override - public void unregister() { - for (TaskWorker taskWorker : taskWorkers) { - taskWorker.stopWorker(); - } - taskWorkers.clear(); - - /* maybe add unfinished tasks to new pool? */ - taskQueue.clear(); - } - - /* controller thread */ - public void control() { - while (YYStal.mainThread().isAlive()) { - - boolean allBusy = true; - for (TaskWorker taskWorker : taskWorkers) { - if (!taskWorker.isBusy()) { - allBusy = false; - break; - } - } - - /* if all workers are busy, adds new workers on the way */ - if (allBusy && workerCount() < maxWorkers) { - final TaskWorker taskWorker = new TaskWorker(); - taskWorkers.add(taskWorker); - taskWorker.start(); - } - - if (!waitingTasks.isEmpty()) { - try { - Iterator> waitingTasksIterator = waitingTasks.entrySet().iterator(); - long time = System.currentTimeMillis(); - while (waitingTasksIterator.hasNext()) { - Map.Entry taskTuple = waitingTasksIterator.next(); - if (taskTuple.getValue() < time) { - taskQueue.add(taskTuple.getKey()); - waitingTasksIterator.remove(); - } - } - } catch (ConcurrentModificationException e) { - e.printStackTrace(); - } - } - - - - /* if a worker is free for some time removes the worker */ - if (!allBusy && workerCount() > minWorkers) { - long time = System.currentTimeMillis() - 500 /* if worker is free more than 500ms */; - Iterator taskWorkerIterator = taskWorkers.iterator(); - while (taskWorkerIterator.hasNext()) { - if (workerCount() > minWorkers) { - final TaskWorker taskWorker = taskWorkerIterator.next(); - if (taskWorker.lastTaskFinish() < time) { - taskWorkerIterator.remove(); - } - } - } - } - - /* waits */ - kThread.sleep(YYStal.setting(YSettings.TASKPOOL_CONTROL_CHECK_DELAY)); - } - } - - /* runs the function async */ - @Override - public Task run(IFunction function, Future future) { - final Task task = new Task(function, future); - taskQueue.add(task); - return task; - } - - @Override - public Task run_w(IFunction function, Future future, long after) { - if (after <= 0) { - return run(function, future); - } - final Task task = new Task(function, future); - waitingTasks.put(task, System.currentTimeMillis() + after); - return task; - } - - @Override - public TaskWorker getWorker() { - Thread thread = Thread.currentThread(); - Iterator taskWorkerIterator = taskWorkers.iterator(); - while (taskWorkerIterator.hasNext()) { - final TaskWorker taskWorker = taskWorkerIterator.next(); - if (taskWorker == thread) - return taskWorker; - } - return null; - } - - @Override - public TaskWorker getWorker(Task task) { - Iterator taskWorkerIterator = taskWorkers.iterator(); - while (taskWorkerIterator.hasNext()) { - final TaskWorker taskWorker = taskWorkerIterator.next(); - if (taskWorker.currentTask() == task) - return taskWorker; - } - return null; - } - - - @Override - public void stopWorker(TaskWorker worker, boolean abort) { - Iterator taskWorkerIterator = taskWorkers.iterator(); - while (taskWorkerIterator.hasNext()) { - final TaskWorker taskWorker = taskWorkerIterator.next(); - if (taskWorker == worker) { - taskWorkerIterator.remove(); - break; - } - } - if (abort) - worker.abortWorker(); - else - worker.stopWorker(); - } - - @Override - public void stopWorker(TaskWorker worker) { - stopWorker(worker, false); - } - - @Override - public void newWorker() { - final TaskWorker taskWorker = new TaskWorker(); - taskWorkers.add(taskWorker); - taskWorker.start(); - } - - @Override - public int workerCount() { - return taskWorkers.size(); - } - - @Override - public Task nextTask() { - return taskQueue.poll(); - } -} diff --git a/src/pisi/unitedmeows/yystal/parallel/utils/YTimer.java b/src/pisi/unitedmeows/yystal/parallel/utils/YTimer.java deleted file mode 100644 index 05af1bc..0000000 --- a/src/pisi/unitedmeows/yystal/parallel/utils/YTimer.java +++ /dev/null @@ -1,39 +0,0 @@ -package pisi.unitedmeows.yystal.parallel.utils; - -import pisi.unitedmeows.yystal.parallel.Async; -import pisi.unitedmeows.yystal.parallel.Promise; - -/* runs the method every x milliseconds */ -public abstract class YTimer { - - private Promise promise; - private long interval; - - public YTimer(final long _interval) { - setInterval(_interval); - } - - public abstract void tick(); - - public YTimer start() { - if (promise == null || !promise.isValid()) { - promise = Async.async_loop_w(this::tick, interval); - } - return this; - } - - public YTimer stop() { - promise.stop(); - return this; - } - - public YTimer setInterval(final long _interval) { - interval = _interval; - if (promise != null && promise.isValid()) { - promise.stop(); - promise = Async.async_loop_w(this::tick, interval); - } - return this; - } - -} diff --git a/src/pisi/unitedmeows/yystal/sql/YDatabaseClient.java b/src/pisi/unitedmeows/yystal/sql/YDatabaseClient.java deleted file mode 100644 index 9d2877c..0000000 --- a/src/pisi/unitedmeows/yystal/sql/YDatabaseClient.java +++ /dev/null @@ -1,115 +0,0 @@ -package pisi.unitedmeows.yystal.sql; - - -import pisi.unitedmeows.yystal.YYStal; -import pisi.unitedmeows.yystal.logger.impl.YLogger; -import pisi.unitedmeows.yystal.parallel.IState; - -import java.sql.*; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class YDatabaseClient { - - private boolean connected; - private Connection connection; - private final java.lang.Object actionLock = new java.lang.Object(); - - - public YDatabaseClient(String username, String password, String database, String host, int port) { - try { - synchronized(this) { - if (connection != null && !connection.isClosed()) { - return; - } - - connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + "?characterEncoding=latin1&useConfigs=maxPerformance", username, password); - connected = true; - } - } catch (Exception ex) { - connected = false; - } - } - - public YDatabaseClient(String username, String password, String database, String host) { - this(username, password, database, host, 3306); - } - - public YDatabaseClient(String username, String password, String database) { - this(username, password, database, "localhost", 3306); - } - - public boolean execute(String sql) { - PreparedStatement command = null; - try { - command = connection.prepareStatement(sql); - return command.execute(); - } catch (SQLException e) { - return false; - } - } - - public boolean execute(YSQLCommand sql) { - return execute(sql.getHooked()); - } - - public List> select(YSQLCommand sql, String... columnNames) { - return select(sql.getHooked(), columnNames); - } - - public List> select(String sql) { - synchronized(actionLock) { - try { - PreparedStatement command = connection.prepareStatement(sql); - ResultSet resultSet = command.executeQuery(); - List> list = new ArrayList<>(); - final int columnCount = command.getMetaData().getColumnCount(); - while (resultSet.next()) { - List dataList = new ArrayList<>(); - for (int i = 0; i < columnCount; i++) { - dataList.add(i, resultSet.getObject(i)); - } - list.add(dataList); - } - return list; - } catch (SQLException e) { - return new ArrayList<>(); - } - } - } - - public List> select(String sql, String... columnNames) { - synchronized(actionLock) { - try { - PreparedStatement command = connection.prepareStatement(sql); - ResultSet resultSet = command.executeQuery(); - List> list = new ArrayList<>(); - while (resultSet.next()) { - Map dataMap = new HashMap<>(); - for (String column : columnNames) { - dataMap.put(column, resultSet.getObject(column)); - } - list.add(dataMap); - } - return list; - } catch (SQLException e) { - return new ArrayList<>(); - } - } - } - - public boolean connected() { - return connected; - } - - public Connection connection() { - return connection; - } - - /* public boolean insertMulti(String tableName, List> dataList, String... columns) { - String sql = "INSERT INTO " + tableName + "(" + String.join(",", columns) + " VALUES "; - - }*/ -} diff --git a/src/pisi/unitedmeows/yystal/sql/YSQLCommand.java b/src/pisi/unitedmeows/yystal/sql/YSQLCommand.java deleted file mode 100644 index 6eacaac..0000000 --- a/src/pisi/unitedmeows/yystal/sql/YSQLCommand.java +++ /dev/null @@ -1,61 +0,0 @@ -package pisi.unitedmeows.yystal.sql; - -import pisi.unitedmeows.yystal.clazz.HookClass; -import pisi.unitedmeows.yystal.hook.YString; - -import java.util.Date; - -public class YSQLCommand extends HookClass { - - public YSQLCommand(String input) { - hooked = input; - } - - public YSQLCommand putString(String data) { - putRaw("'" + data + "'"); - return this; - } - - public YSQLCommand putInt(int data) { - return putRaw(data); - } - - public YSQLCommand putDouble(double data) { - return putRaw(data); - } - - public YSQLCommand putFloat(float data) { - return putRaw(data); - } - - public YSQLCommand putBool(boolean bool) { - return putRaw(bool ? 1 : 0); - } - - public YSQLCommand putDate(Date date) { - // ? - return this; - } - - public YSQLCommand put(Object data) { - if (data instanceof String) { - return putString((String)data); - } else if (data instanceof Integer) { - return putInt((int) data); - } else if (data instanceof Boolean) { - return putBool((boolean) data); - } else { - return putRaw(data); - } - } - - public YSQLCommand putRaw(Object data) { - hooked = new YString(hooked).replaceFirst('^', String.valueOf(data)).toString(); - return this; - } - - @Override - public String getHooked() { - return super.getHooked(); - } -} diff --git a/src/pisi/unitedmeows/yystal/sql/objects/DBTable.java b/src/pisi/unitedmeows/yystal/sql/objects/DBTable.java deleted file mode 100644 index 19b550c..0000000 --- a/src/pisi/unitedmeows/yystal/sql/objects/DBTable.java +++ /dev/null @@ -1,5 +0,0 @@ -package pisi.unitedmeows.yystal.sql.objects; - -public class DBTable { - -} diff --git a/src/pisi/unitedmeows/yystal/ui/YWindow.java b/src/pisi/unitedmeows/yystal/ui/YWindow.java deleted file mode 100644 index 44a03af..0000000 --- a/src/pisi/unitedmeows/yystal/ui/YWindow.java +++ /dev/null @@ -1,243 +0,0 @@ -package pisi.unitedmeows.yystal.ui; - -import static org.lwjgl.glfw.GLFW.*; -import static org.lwjgl.opengl.GL11.*; -import static org.lwjgl.system.MemoryStack.stackPush; -import static org.lwjgl.system.MemoryUtil.NULL; - -import java.awt.Color; -import java.nio.FloatBuffer; -import java.nio.IntBuffer; - -import org.lwjgl.BufferUtils; -import org.lwjgl.glfw.GLFWCursorPosCallback; -import org.lwjgl.glfw.GLFWVidMode; -import org.lwjgl.opengl.GL; -import org.lwjgl.opengl.GL11; -import org.lwjgl.system.MemoryStack; - -import pisi.unitedmeows.yystal.YYStal; -import pisi.unitedmeows.yystal.clazz.prop; -import pisi.unitedmeows.yystal.ui.element.YContainer; -import pisi.unitedmeows.yystal.ui.font.Batch; -import pisi.unitedmeows.yystal.ui.font.Shader; -import pisi.unitedmeows.yystal.ui.font.data.CFont; -import pisi.unitedmeows.yystal.ui.font.data.CharInfo; -import pisi.unitedmeows.yystal.ui.utils.*; -import pisi.unitedmeows.yystal.utils.Vector2f; - -public class YWindow extends YContainer { - - private final Vector2f /* yystal vector2f :D.d:D */ mouseCoords = new Vector2f(-1F, -1F); - private final Vector2f mouseDelta = new Vector2f(-1F, -1F); - private final String title; - private boolean resizable; - private long window; - private Thread windowThread = null; - public static FloatBuffer fbModel = BufferUtils.createFloatBuffer(16); - public static FloatBuffer fbView = BufferUtils.createFloatBuffer(16); - public static FloatBuffer fbProjection = BufferUtils.createFloatBuffer(16); - - private CFont font; - public prop backgroundColor = new prop<>(Color.RED); - - - private String getPathFromAssets(final String file) { - if (file == null) /* add check for linux */ - return "/" + Object.class.getResource("/pisi/unitedmeows/yystal/ui/assets/").toString().substring(6); - return "/" + Object.class.getResource(String.format("/pisi/unitedmeows/yystal/ui/assets/%s", file)).toString().substring(6) /* to get rid of file:/ */; - } - - public YWindow(final String _title, final int _width, final int _height) { - super(new Vertex2f(0, 0), new Vector2f((float)_width, (float)_height), YOrigin.TOP_LEFT); - title = _title; - } - - public void open() { - windowThread = new Thread(this::_open); - windowThread.start(); - } - - public int width() { return Math.round(size.getX()); } - - public int height() { return Math.round(size.getY()); } - - public YWindow width(final int _width) { - size(_width, size.getY()); - return this; - } - - public YWindow height(final int _height) { - size(size.getX(), _height); - return this; - } - - public YWindow setResizable(final boolean state) { - resizable = state; - if (windowThread != null) { - glfwWindowHint(GLFW_RESIZABLE, state ? GLFW_TRUE : GLFW_FALSE); - } - return this; - } - - public YWindow size(final float _width, final float _height) { - size.setX(_width); - size.setY(_height); - glfwSetWindowSize(window, Math.round(size.getX()), Math.round(size.getY())); - return this; - } - - public void hide() { - if (windowThread != null) { - glfwHideWindow(window); - } - } - - public void show() { - if (windowThread != null) { - glfwShowWindow(window); - } - } - - public boolean isResizable() { return resizable; } - - @SuppressWarnings("resource") // stfu ide - private void _open() { - if (!glfwInit()) /* todo: throw an exception */ - return; - glfwDefaultWindowHints(); - /* - * antialiasing - */ - glfwWindowHint(GLFW_SAMPLES, 4); - glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); - glfwWindowHint(GLFW_RESIZABLE, resizable ? GLFW_TRUE : GLFW_FALSE); - - window = glfwCreateWindow(width(), height(), title, NULL, NULL); - if (window == NULL) /* throw an exception */ - return; - glfwMakeContextCurrent(window); - GL.createCapabilities(); - glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> { - if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE) { - glfwSetWindowShouldClose(window, true); - } - }); - glfwSetCursorPosCallback(window, new GLFWCursorPosCallback() { - @Override - public void invoke(final long window, final double xpos, final double ypos) { - mouseDelta.setX((float) (xpos - mouseCoords.getX())); - mouseDelta.setY((float) (ypos - mouseCoords.getY())); - mouseCoords.setY((float) ypos); - mouseCoords.setX((float) xpos); - } - }); - // center the window - // add several options like (CENTER, RANDOM, LEFT, RIGHT) - try (MemoryStack stack = stackPush()) { - final IntBuffer pWidth = stack.mallocInt(1); - final IntBuffer pHeight = stack.mallocInt(1); - glfwGetWindowSize(window, pWidth, pHeight); - final GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor()); - glfwSetWindowPos(window, (vidmode.width() - pWidth.get(0)) / 2, (vidmode.height() - pHeight.get(0)) / 2); - } - // enabling vsync <- cringe - glfwSwapInterval(1); - glfwShowWindow(window); - YYStal.registerWindow(this); - // capabilities should be created last afaik... - font = new CFont(getPathFromAssets("font.ttf"), 64); - loop(); - } - - public void close() { glfwSetWindowShouldClose(window, true); } - - private void loop() { - int glErrCode; - final Shader fontShader = new Shader(getPathFromAssets(null), getPathFromAssets("fontShader.vertex"), getPathFromAssets("fontShader.fragment")); - final Shader sdfShader = new Shader(getPathFromAssets(null), getPathFromAssets("sdfShader.vertex"), getPathFromAssets("sdfShader.fragment")); - final Batch batch = new Batch(); - batch.shader = fontShader; - batch.sdfShader = sdfShader; - batch.font = font; - batch.initBatch(this); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - final CharInfo oneQuad = new CharInfo(0, 0, 1, 1); - oneQuad.calculateTextureCoordinates(1, 1); - double previousTime = glfwGetTime(); - - - int frameCount = 0; - int lastCalculation = 0; - glEnableClientState(GL11.GL_VERTEX_ARRAY); - glMatrixMode(GL_PROJECTION); - glOrtho(0, width(), height(), 0, 1, -1); - glMatrixMode(GL_MODELVIEW); - glDisable(GL_TEXTURE_2D); - while (!glfwWindowShouldClose(window)) { - - - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - glClearColor(backgroundColor.get().getRed(), backgroundColor.get().getGreen(), backgroundColor.get().getBlue(), 1.0F); - // rendering here - final int mouseX = mouseCoords.getX().intValue(); - final int mouseY = height() - mouseCoords.getY().intValue(); - final double currentTime = glfwGetTime(); - frameCount++; - if (currentTime - previousTime >= 1.0) { - lastCalculation = frameCount; - frameCount = 0; - previousTime = currentTime; - } - - final Rectangle rectangle = new Rectangle(0, 0, 1920, 1080); - batch.addText(String.format("fps -> %s", lastCalculation), 0, 0, 1F, getRainbow(0L, 1F).getRGB()); - batch.addText("font 2x :D", mouseX, mouseY + 70, 2.0F, 7964363); - batch.addText("font :D", mouseX, mouseY, 1.0F, 0xAA01BB); - batch.addText("font with 0.5 scale???", mouseX, mouseY - 35, 5, getRainbow(0L, 1F).getRGB()); - batch.addText("font with 0.25 scale???", mouseX, mouseY - 60, 0.25F, 8281781); - batch.addText("font with 0.125 scale???", mouseX, mouseY - 70, 0.125F, -1); - batch.flushBatch(); - - if (!NullCheck.CHECK.isNull(rectangle)) { - rectangle.draw(-8345634); - } - - - - - glfwPollEvents(); - glfwSwapBuffers(window); - glErrCode = glGetError(); - if (glErrCode != GL_NO_ERROR) { - //System.out.printf("OpenGL Error %s %s", glErrCode, System.lineSeparator()); - } - } - } - - @Override - public void draw() { - - } - - @Override - public boolean isMouseOver(float mouseX, float mouseY) { - return glfwGetWindowAttrib(window, GLFW_FOCUSED) == 1; - } - - public float mouseX() { - return mouseCoords.getX(); - } - - public float mouseY() { - return mouseCoords.getY(); - } - - public Color getRainbow(final long offset, final float fade) { - final float hue = (System.nanoTime() + offset) / 5.0E9F % 1.0F; - final long color = Long.parseLong(Integer.toHexString(Color.HSBtoRGB(hue, 1.0F, 1.0F)), 16); - final Color c = new Color((int) color); - return new Color(c.getRed() / 255.0F * fade, c.getGreen() / 255.0F * fade, c.getBlue() / 255.0F * fade, c.getAlpha() / 255.0F); - } -} \ No newline at end of file diff --git a/src/pisi/unitedmeows/yystal/ui/assets/font.ttf b/src/pisi/unitedmeows/yystal/ui/assets/font.ttf deleted file mode 100644 index ace7263..0000000 Binary files a/src/pisi/unitedmeows/yystal/ui/assets/font.ttf and /dev/null differ diff --git a/src/pisi/unitedmeows/yystal/ui/assets/fontShader.fragment b/src/pisi/unitedmeows/yystal/ui/assets/fontShader.fragment deleted file mode 100644 index e673539..0000000 --- a/src/pisi/unitedmeows/yystal/ui/assets/fontShader.fragment +++ /dev/null @@ -1,18 +0,0 @@ -#version 320 es - -#ifdef GL_ES -precision mediump float; -#endif - -in vec2 fTexCoords; -in vec3 fColor; - -uniform sampler2D uFontTexture; - -out vec4 color; - -void main() -{ - float c = texture(uFontTexture, fTexCoords).r; - color = vec4(1, 1, 1, c) * vec4(fColor, 1); -} \ No newline at end of file diff --git a/src/pisi/unitedmeows/yystal/ui/assets/fontShader.vertex b/src/pisi/unitedmeows/yystal/ui/assets/fontShader.vertex deleted file mode 100644 index 3201b85..0000000 --- a/src/pisi/unitedmeows/yystal/ui/assets/fontShader.vertex +++ /dev/null @@ -1,21 +0,0 @@ -#version 320 es - -#ifdef GL_ES -precision mediump float; -#endif - -layout(location=0) in vec2 aPos; -layout(location=1) in vec3 aColor; -layout(location=2) in vec2 aTexCoords; - -out vec2 fTexCoords; -out vec3 fColor; - -uniform mat4 uProjection; - -void main() -{ - fTexCoords = aTexCoords; - fColor = aColor; - gl_Position = uProjection * vec4(aPos, -5, 1); -} \ No newline at end of file diff --git a/src/pisi/unitedmeows/yystal/ui/assets/sdfShader.fragment b/src/pisi/unitedmeows/yystal/ui/assets/sdfShader.fragment deleted file mode 100644 index 25159c4..0000000 --- a/src/pisi/unitedmeows/yystal/ui/assets/sdfShader.fragment +++ /dev/null @@ -1,30 +0,0 @@ -#version 320 es - -#ifdef GL_ES -precision mediump float; -#endif - - -in vec2 fTexCoords; -in vec3 fColor; - -uniform sampler2D uFontTexture; - -out vec4 color; - -void main() -{ - float upperPointCutoff = 0.5; - float midpointCutoff = 0.49; - float c = texture(uFontTexture, fTexCoords).r; - if (c > upperPointCutoff) - color = vec4(1, 1, 1, 1) * vec4(fColor, 1); - else if (c > midpointCutoff) - { - // [0.45, 5] -> [0, 1] - float smoothC = smoothstep(midpointCutoff, upperPointCutoff, c); - color = vec4(1, 1, 1, smoothC) * vec4(fColor, 1); - } - else - color = vec4(0, 0, 0, 0); -} \ No newline at end of file diff --git a/src/pisi/unitedmeows/yystal/ui/assets/sdfShader.vertex b/src/pisi/unitedmeows/yystal/ui/assets/sdfShader.vertex deleted file mode 100644 index 3201b85..0000000 --- a/src/pisi/unitedmeows/yystal/ui/assets/sdfShader.vertex +++ /dev/null @@ -1,21 +0,0 @@ -#version 320 es - -#ifdef GL_ES -precision mediump float; -#endif - -layout(location=0) in vec2 aPos; -layout(location=1) in vec3 aColor; -layout(location=2) in vec2 aTexCoords; - -out vec2 fTexCoords; -out vec3 fColor; - -uniform mat4 uProjection; - -void main() -{ - fTexCoords = aTexCoords; - fColor = aColor; - gl_Position = uProjection * vec4(aPos, -5, 1); -} \ No newline at end of file diff --git a/src/pisi/unitedmeows/yystal/ui/element/YContainer.java b/src/pisi/unitedmeows/yystal/ui/element/YContainer.java deleted file mode 100644 index 9e6acab..0000000 --- a/src/pisi/unitedmeows/yystal/ui/element/YContainer.java +++ /dev/null @@ -1,49 +0,0 @@ -package pisi.unitedmeows.yystal.ui.element; - -import pisi.unitedmeows.yystal.ui.utils.Vertex2f; -import pisi.unitedmeows.yystal.ui.utils.YOrigin; -import pisi.unitedmeows.yystal.utils.Vector2f; - -import java.util.ArrayList; -import java.util.List; - -public abstract class YContainer extends YElement { - - protected Vertex2f location; - protected YOrigin origin; - protected Vector2f size; - private final List elements; - - - public YContainer(Vertex2f _location, Vector2f _size, YOrigin _origin) { - location = _location; - size = _size; - origin = _origin; - elements = new ArrayList<>(); - } - - - public YOrigin origin() { - return origin; - } - - public Vector2f size() { - return size; - } - - public Vertex2f location() { - return location; - } - - public void setLocation(Vertex2f location) { - this.location = location; - } - - public void setOrigin(YOrigin origin) { - this.origin = origin; - } - - public void setSize(Vector2f size) { - this.size = size; - } -} diff --git a/src/pisi/unitedmeows/yystal/ui/element/YElement.java b/src/pisi/unitedmeows/yystal/ui/element/YElement.java deleted file mode 100644 index 869dfab..0000000 --- a/src/pisi/unitedmeows/yystal/ui/element/YElement.java +++ /dev/null @@ -1,67 +0,0 @@ -package pisi.unitedmeows.yystal.ui.element; - -import pisi.unitedmeows.yystal.clazz.prop; -import pisi.unitedmeows.yystal.ui.YWindow; -import pisi.unitedmeows.yystal.ui.utils.Vertex2f; -import pisi.unitedmeows.yystal.ui.utils.YOrigin; - -public abstract class YElement -{ - private Vertex2f location; - private YOrigin origin; - protected YContainer container; - - public final prop currentWindow = new prop(null) { - @Override - public YWindow get() { - if (value == null) { - YElement owner = instance(); - while (owner.container != null) { - owner = owner.container; - } - if (owner instanceof YWindow) { - value = (YWindow) owner; - } - } - return value; - } - - @Deprecated - @Override - public void set(YWindow newValue) { } - }; - - public final prop isMouseOver = new prop() { - @Override - public Boolean get() { - YWindow window = currentWindow.get(); - if (window != null) { - return isMouseOver(window.mouseX(), window.mouseY()); - } - return false; - } - - @Deprecated - @Override - public void set(Boolean newValue) {} - }; - - public abstract void draw(); - public abstract boolean isMouseOver(final float mouseX, final float mouseY); - - public Vertex2f location() { - return location; - } - - public float getRenderX() { - switch (origin) { - - } - return -1; - } - - public YElement instance() { - return this; - } - -} diff --git a/src/pisi/unitedmeows/yystal/ui/font/Batch.java b/src/pisi/unitedmeows/yystal/ui/font/Batch.java deleted file mode 100644 index ddd60b6..0000000 --- a/src/pisi/unitedmeows/yystal/ui/font/Batch.java +++ /dev/null @@ -1,148 +0,0 @@ -package pisi.unitedmeows.yystal.ui.font; - -import static org.lwjgl.opengl.GL11.GL_FLOAT; -import static org.lwjgl.opengl.GL11.GL_TRIANGLES; -import static org.lwjgl.opengl.GL11.GL_UNSIGNED_INT; -import static org.lwjgl.opengl.GL11.glBindTexture; -import static org.lwjgl.opengl.GL11.glDrawElements; -import static org.lwjgl.opengl.GL13.GL_TEXTURE0; -import static org.lwjgl.opengl.GL13.glActiveTexture; -import static org.lwjgl.opengl.GL15.GL_ARRAY_BUFFER; -import static org.lwjgl.opengl.GL15.GL_DYNAMIC_DRAW; -import static org.lwjgl.opengl.GL15.GL_STATIC_DRAW; -import static org.lwjgl.opengl.GL15.glBindBuffer; -import static org.lwjgl.opengl.GL15.glBufferData; -import static org.lwjgl.opengl.GL15.glBufferSubData; -import static org.lwjgl.opengl.GL15C.GL_ELEMENT_ARRAY_BUFFER; -import static org.lwjgl.opengl.GL15C.glGenBuffers; -import static org.lwjgl.opengl.GL20.glEnableVertexAttribArray; -import static org.lwjgl.opengl.GL20.glVertexAttribPointer; -import static org.lwjgl.opengl.GL30.glBindVertexArray; -import static org.lwjgl.opengl.GL30.glGenVertexArrays; -import static org.lwjgl.opengl.GL31.GL_TEXTURE_BUFFER; - -import org.joml.Matrix4f; -import org.lwjgl.opengl.GL15; - -import pisi.unitedmeows.yystal.ui.YWindow; -import pisi.unitedmeows.yystal.ui.font.data.CFont; -import pisi.unitedmeows.yystal.ui.font.data.CharInfo; -// TODO: add alpha support - -public class Batch { - private final int[] indices = { 0, 1, 3, 1, 2, 3 }; - public static int BATCH_SIZE = 100 , VERTEX_SIZE = 7; - public float[] vertices = new float[BATCH_SIZE * VERTEX_SIZE]; - private final Matrix4f projection = new Matrix4f(); - public int vao , vbo , size; - public Shader shader , sdfShader; - public CFont font; - public YWindow yWindow; - - public void generateEbo() { - final int elementSize = BATCH_SIZE * 3; - final int[] elementBuffer = new int[elementSize]; - for (int i = 0; i < elementSize; i++) { elementBuffer[i] = indices[(i % 6)] + ((i / 6) * 4); } - final int ebo = glGenBuffers(); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); - glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, elementBuffer, GL_STATIC_DRAW); - } - - public void initBatch(final YWindow yWindow) { - this.yWindow = yWindow; - projection.identity(); - projection.ortho(0, yWindow.width(), 0, yWindow.height(), 1F, 100F); - vao = glGenVertexArrays(); - glBindVertexArray(vao); - vbo = glGenBuffers(); - glBindBuffer(GL_ARRAY_BUFFER, vbo); - glBufferData(GL_ARRAY_BUFFER, Float.BYTES * VERTEX_SIZE * BATCH_SIZE, GL_DYNAMIC_DRAW); - generateEbo(); - final int stride = 7 * Float.BYTES; - glVertexAttribPointer(0, 2, GL_FLOAT, false, stride, 0); - glEnableVertexAttribArray(0); - glVertexAttribPointer(1, 3, GL_FLOAT, false, stride, 2 * Float.BYTES); - glEnableVertexAttribArray(1); - glVertexAttribPointer(2, 2, GL_FLOAT, false, stride, 5 * Float.BYTES); - glEnableVertexAttribArray(2); - } - - public void flushBatch() { - glBindBuffer(GL_ARRAY_BUFFER, vbo); - glBufferData(GL_ARRAY_BUFFER, Float.BYTES * VERTEX_SIZE * BATCH_SIZE, GL_DYNAMIC_DRAW); - glBufferSubData(GL_ARRAY_BUFFER, 0, vertices); - shader.use(); - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_BUFFER, font.textureId); - sdfShader.uploadTexture("uFontTexture", 0); - sdfShader.uploadMat4f("uProjection", projection); - glBindVertexArray(vao); - glDrawElements(GL_TRIANGLES, size * 6, GL_UNSIGNED_INT, 0); - size = 0; - } - - public void addCharacter(final float x, final float y, final float scale, final CharInfo charInfo, final int rgb) { - if (size >= BATCH_SIZE - 4) { - flushBatch(); - } - final float r = ((rgb >> 16) & 0xFF) / 255.0F; - final float g = ((rgb >> 8) & 0xFF) / 255.0F; - final float b = ((rgb >> 0) & 0xFF) / 255.0F; - final float x0 = x; - final float y0 = y; - final float x1 = x + scale * charInfo.width; - final float y1 = y + scale * charInfo.height; - final float ux0 = charInfo.textureCoordinates[0].getX(); - final float uy0 = charInfo.textureCoordinates[0].getY(); - final float ux1 = charInfo.textureCoordinates[1].getX(); - final float uy1 = charInfo.textureCoordinates[1].getY(); - int index = size * 7; - vertices[index] = x1; - vertices[index + 1] = y0; - vertices[index + 2] = r; - vertices[index + 3] = g; - vertices[index + 4] = b; - vertices[index + 5] = ux1; - vertices[index + 6] = uy0; - index += 7; - vertices[index] = x1; - vertices[index + 1] = y1; - vertices[index + 2] = r; - vertices[index + 3] = g; - vertices[index + 4] = b; - vertices[index + 5] = ux1; - vertices[index + 6] = uy1; - index += 7; - vertices[index] = x0; - vertices[index + 1] = y1; - vertices[index + 2] = r; - vertices[index + 3] = g; - vertices[index + 4] = b; - vertices[index + 5] = ux0; - vertices[index + 6] = uy1; - index += 7; - vertices[index] = x0; - vertices[index + 1] = y0; - vertices[index + 2] = r; - vertices[index + 3] = g; - vertices[index + 4] = b; - vertices[index + 5] = ux0; - vertices[index + 6] = uy0; - size += 4; - } - - public void addText(final String text, int x, final int y, final float scale, final int rgb) { - for (int i = 0; i < text.length(); i++) { - final char c = text.charAt(i); - final CharInfo charInfo = font.getCharacter(c); - if (charInfo.width == 0) { - System.out.println("Unknown character " + c); - continue; - } - final float xPos = x; - final float yPos = y; - addCharacter(xPos, yPos, scale, charInfo, rgb); - x += charInfo.width * scale; - } - } -} diff --git a/src/pisi/unitedmeows/yystal/ui/font/Shader.java b/src/pisi/unitedmeows/yystal/ui/font/Shader.java deleted file mode 100644 index d32ad98..0000000 --- a/src/pisi/unitedmeows/yystal/ui/font/Shader.java +++ /dev/null @@ -1,179 +0,0 @@ -package pisi.unitedmeows.yystal.ui.font; - -import static org.lwjgl.opengl.GL11.GL_FALSE; -import static org.lwjgl.opengl.GL20.GL_COMPILE_STATUS; -import static org.lwjgl.opengl.GL20.GL_FRAGMENT_SHADER; -import static org.lwjgl.opengl.GL20.GL_INFO_LOG_LENGTH; -import static org.lwjgl.opengl.GL20.GL_LINK_STATUS; -import static org.lwjgl.opengl.GL20.GL_VERTEX_SHADER; -import static org.lwjgl.opengl.GL20.glAttachShader; -import static org.lwjgl.opengl.GL20.glCompileShader; -import static org.lwjgl.opengl.GL20.glCreateProgram; -import static org.lwjgl.opengl.GL20.glCreateShader; -import static org.lwjgl.opengl.GL20.glGetProgramInfoLog; -import static org.lwjgl.opengl.GL20.glGetProgrami; -import static org.lwjgl.opengl.GL20.glGetShaderInfoLog; -import static org.lwjgl.opengl.GL20.glGetShaderi; -import static org.lwjgl.opengl.GL20.glGetUniformLocation; -import static org.lwjgl.opengl.GL20.glLinkProgram; -import static org.lwjgl.opengl.GL20.glShaderSource; -import static org.lwjgl.opengl.GL20.glUniform1f; -import static org.lwjgl.opengl.GL20.glUniform1i; -import static org.lwjgl.opengl.GL20.glUniform1iv; -import static org.lwjgl.opengl.GL20.glUniform2f; -import static org.lwjgl.opengl.GL20.glUniform3f; -import static org.lwjgl.opengl.GL20.glUniform4f; -import static org.lwjgl.opengl.GL20.glUniformMatrix3fv; -import static org.lwjgl.opengl.GL20.glUniformMatrix4fv; -import static org.lwjgl.opengl.GL20.glUseProgram; - -import java.io.IOException; -import java.nio.FloatBuffer; -import java.nio.file.Files; -import java.nio.file.Paths; - -import org.joml.Matrix3f; -import org.joml.Matrix4f; -import org.joml.Vector2f; -import org.joml.Vector3f; -import org.joml.Vector4f; -import org.lwjgl.BufferUtils; - -public class Shader { - private int shaderProgramID; - private boolean beingUsed = false; - private String vertexSource; - private String fragmentSource; - private final String filepath; - - public Shader(final String realPath, final String vertex, final String fragment) { - this.filepath = realPath; - try { - final String vertexa = new String(Files.readAllBytes(Paths.get(vertex))); - vertexSource = vertexa; - final String fragmento = new String(Files.readAllBytes(Paths.get(fragment))); - fragmentSource = fragmento; - } catch (final IOException e) { - e.printStackTrace(); - assert false : "Error: Could not open file for shader: '" + filepath + "'"; - } - compile(); - } - - public void compile() { - // ============================================================ - // Compile and link shaders - // ============================================================ - int vertexID , fragmentID; - // First load and compile the vertex shader - vertexID = glCreateShader(GL_VERTEX_SHADER); - // Pass the shader source to the GPU - glShaderSource(vertexID, vertexSource); - glCompileShader(vertexID); - // Check for errors in compilation - int success = glGetShaderi(vertexID, GL_COMPILE_STATUS); - if (success == GL_FALSE) { - final int len = glGetShaderi(vertexID, GL_INFO_LOG_LENGTH); - System.out.println("ERROR: '" + filepath + "'\n\tVertex shader compilation failed."); - System.out.println(glGetShaderInfoLog(vertexID, len)); - assert false : ""; - } - // First load and compile the vertex shader - fragmentID = glCreateShader(GL_FRAGMENT_SHADER); - // Pass the shader source to the GPU - glShaderSource(fragmentID, fragmentSource); - glCompileShader(fragmentID); - // Check for errors in compilation - success = glGetShaderi(fragmentID, GL_COMPILE_STATUS); - if (success == GL_FALSE) { - final int len = glGetShaderi(fragmentID, GL_INFO_LOG_LENGTH); - System.out.println("ERROR: '" + filepath + "'\n\tFragment shader compilation failed."); - System.out.println(glGetShaderInfoLog(fragmentID, len)); - assert false : ""; - } - // Link shaders and check for errors - shaderProgramID = glCreateProgram(); - glAttachShader(shaderProgramID, vertexID); - glAttachShader(shaderProgramID, fragmentID); - glLinkProgram(shaderProgramID); - // Check for linking errors - success = glGetProgrami(shaderProgramID, GL_LINK_STATUS); - if (success == GL_FALSE) { - final int len = glGetProgrami(shaderProgramID, GL_INFO_LOG_LENGTH); - System.out.println("ERROR: '" + filepath + "'\n\tLinking of shaders failed."); - System.out.println(glGetProgramInfoLog(shaderProgramID, len)); - assert false : ""; - } - } - - public void use() { - if (!beingUsed) { - // Bind shader program - glUseProgram(shaderProgramID); - beingUsed = true; - } - } - - public void detach() { - glUseProgram(0); - beingUsed = false; - } - - public void uploadMat4f(final String varName, final Matrix4f mat4) { - final int varLocation = glGetUniformLocation(shaderProgramID, varName); - use(); - final FloatBuffer matBuffer = BufferUtils.createFloatBuffer(16); - mat4.get(matBuffer); - glUniformMatrix4fv(varLocation, false, matBuffer); - } - - public void uploadMat3f(final String varName, final Matrix3f mat3) { - final int varLocation = glGetUniformLocation(shaderProgramID, varName); - use(); - final FloatBuffer matBuffer = BufferUtils.createFloatBuffer(9); - mat3.get(matBuffer); - glUniformMatrix3fv(varLocation, false, matBuffer); - } - - public void uploadVec4f(final String varName, final Vector4f vec) { - final int varLocation = glGetUniformLocation(shaderProgramID, varName); - use(); - glUniform4f(varLocation, vec.x, vec.y, vec.z, vec.w); - } - - public void uploadVec3f(final String varName, final Vector3f vec) { - final int varLocation = glGetUniformLocation(shaderProgramID, varName); - use(); - glUniform3f(varLocation, vec.x, vec.y, vec.z); - } - - public void uploadVec2f(final String varName, final Vector2f vec) { - final int varLocation = glGetUniformLocation(shaderProgramID, varName); - use(); - glUniform2f(varLocation, vec.x, vec.y); - } - - public void uploadFloat(final String varName, final float val) { - final int varLocation = glGetUniformLocation(shaderProgramID, varName); - use(); - glUniform1f(varLocation, val); - } - - public void uploadInt(final String varName, final int val) { - final int varLocation = glGetUniformLocation(shaderProgramID, varName); - use(); - glUniform1i(varLocation, val); - } - - public void uploadTexture(final String varName, final int slot) { - final int varLocation = glGetUniformLocation(shaderProgramID, varName); - use(); - glUniform1i(varLocation, slot); - } - - public void uploadIntArray(final String varName, final int[] array) { - final int varLocation = glGetUniformLocation(shaderProgramID, varName); - use(); - glUniform1iv(varLocation, array); - } -} diff --git a/src/pisi/unitedmeows/yystal/ui/font/data/CFont.java b/src/pisi/unitedmeows/yystal/ui/font/data/CFont.java deleted file mode 100644 index f88eb20..0000000 --- a/src/pisi/unitedmeows/yystal/ui/font/data/CFont.java +++ /dev/null @@ -1,132 +0,0 @@ -package pisi.unitedmeows.yystal.ui.font.data; - -import static org.lwjgl.opengl.GL11.GL_LINEAR; -import static org.lwjgl.opengl.GL11.GL_REPEAT; -import static org.lwjgl.opengl.GL11.GL_RGBA; -import static org.lwjgl.opengl.GL11.GL_RGBA8; -import static org.lwjgl.opengl.GL11.GL_TEXTURE_2D; -import static org.lwjgl.opengl.GL11.GL_TEXTURE_MAG_FILTER; -import static org.lwjgl.opengl.GL11.GL_TEXTURE_MIN_FILTER; -import static org.lwjgl.opengl.GL11.GL_TEXTURE_WRAP_S; -import static org.lwjgl.opengl.GL11.GL_TEXTURE_WRAP_T; -import static org.lwjgl.opengl.GL11.GL_UNSIGNED_BYTE; -import static org.lwjgl.opengl.GL11.glGenTextures; -import static org.lwjgl.opengl.GL11.glTexImage2D; -import static org.lwjgl.opengl.GL11.glTexParameteri; - -import java.awt.Color; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics2D; -import java.awt.GraphicsEnvironment; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; -import java.io.File; -import java.nio.ByteBuffer; -import java.util.HashMap; -import java.util.Map; - -import org.lwjgl.BufferUtils; - -public class CFont { - private final String filepath; - private final int fontSize; - private int width , height , lineHeight; - private final Map characterMap; - public int textureId; - - public CFont(final String filepath, final int fontSize) { - this.filepath = filepath; - this.fontSize = fontSize; - this.characterMap = new HashMap<>(); - generateBitmap(); - } - - public CharInfo getCharacter(final int codepoint) { return characterMap.getOrDefault(codepoint, new CharInfo(0, 0, 0, 0)); } - - private Font registerFont(final String fontFile) { - try { - final GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); - final Font font = Font.createFont(Font.TRUETYPE_FONT, new File(filepath)); - ge.registerFont(font); - return font; - } catch (final Exception e) { - e.printStackTrace(); - } - return null; - } - - public void generateBitmap() { - Font font = registerFont(filepath); - if (font == null) { - System.err.println("Font is null @ CFont#generateBitmap"); - return; - } - font = new Font(font.getName(), Font.PLAIN, fontSize); - BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); - Graphics2D g2d = img.createGraphics(); - g2d.setFont(font); - final FontMetrics fontMetrics = g2d.getFontMetrics(); - final int estimatedWidth = (int) Math.sqrt(font.getNumGlyphs()) * font.getSize() + 1; - width = 0; - height = fontMetrics.getHeight(); - lineHeight = fontMetrics.getHeight(); - int x = 0; - int y = (int) (fontMetrics.getHeight() * 1.4F); - for (int i = 0; i < font.getNumGlyphs(); i++) { - if (font.canDisplay(i)) { - final CharInfo charInfo = new CharInfo(x, y, fontMetrics.charWidth(i), fontMetrics.getHeight()); - characterMap.put(i, charInfo); - width = Math.max(x + fontMetrics.charWidth(i), width); - x += charInfo.width; - if (x > estimatedWidth) { - x = 0; - y += fontMetrics.getHeight() * 1.4F; - height += fontMetrics.getHeight() * 1.4F; - } - } - } - height += fontMetrics.getHeight() * 1.4F; - g2d.dispose(); - // Create the real texture - img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - g2d = img.createGraphics(); - g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g2d.setFont(font); - g2d.setColor(Color.WHITE); - for (int i = 0; i < font.getNumGlyphs(); i++) { - if (font.canDisplay(i)) { - final CharInfo info = characterMap.get(i); - info.calculateTextureCoordinates(width, height); - g2d.drawString("" + (char) i, info.sourceX, info.sourceY); - } - } - g2d.dispose(); - uploadTexture(img); - } - - private void uploadTexture(final BufferedImage image) { - // Taken from https://stackoverflow.com/questions/10801016/lwjgl-textures-and-strings - final int[] pixels = new int[image.getHeight() * image.getWidth()]; - image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth()); - final ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * 4); - for (int y = 0; y < image.getHeight(); y++) { - for (int x = 0; x < image.getWidth(); x++) { - final int pixel = pixels[y * image.getWidth() + x]; - final byte alphaComponent = (byte) ((pixel >> 24) & 0xFF); - buffer.put(alphaComponent); - buffer.put(alphaComponent); - buffer.put(alphaComponent); - buffer.put(alphaComponent); - } - } - buffer.flip(); - textureId = glGenTextures(); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); - buffer.clear(); - } -} diff --git a/src/pisi/unitedmeows/yystal/ui/font/data/CharInfo.java b/src/pisi/unitedmeows/yystal/ui/font/data/CharInfo.java deleted file mode 100644 index 67f171b..0000000 --- a/src/pisi/unitedmeows/yystal/ui/font/data/CharInfo.java +++ /dev/null @@ -1,28 +0,0 @@ -package pisi.unitedmeows.yystal.ui.font.data; - - -import pisi.unitedmeows.yystal.utils.Vector2f; - -public class CharInfo { - public int sourceX; - public int sourceY; - public int width; - public int height; - public Vector2f[] textureCoordinates = new Vector2f[4]; - - public CharInfo(final int sourceX, final int sourceY, final int width, final int height) { - this.sourceX = sourceX; - this.sourceY = sourceY; - this.width = width; - this.height = height; - } - - public void calculateTextureCoordinates(final int fontWidth, final int fontHeight) { - final float x0 = (float) sourceX / (float) fontWidth; - final float x1 = (float) (sourceX + width) / (float) fontWidth; - final float y0 = (float) (sourceY - height) / (float) fontHeight; - final float y1 = (float) (sourceY) / (float) fontHeight; - textureCoordinates[0] = new Vector2f(x0, y1); - textureCoordinates[1] = new Vector2f(x1, y0); - } -} diff --git a/src/pisi/unitedmeows/yystal/ui/utils/Mesh.java b/src/pisi/unitedmeows/yystal/ui/utils/Mesh.java deleted file mode 100644 index 554fc87..0000000 --- a/src/pisi/unitedmeows/yystal/ui/utils/Mesh.java +++ /dev/null @@ -1,69 +0,0 @@ -package pisi.unitedmeows.yystal.ui.utils; - -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL15; -import org.lwjgl.opengl.GL20; -import org.lwjgl.opengl.GL30; -import org.lwjgl.system.MemoryUtil; - -import java.nio.FloatBuffer; -import java.nio.IntBuffer; - -public class Mesh { - private Vertex3f[] vertices; - private int[] indices; - private int vao, pbo, ibo; - - public Mesh(Vertex3f[] vertices, int[] indices) { - this.vertices = vertices; - this.indices = indices; - } - - public void create() { - vao = GL30.glGenVertexArrays(); - GL30.glBindVertexArray(vao); - - FloatBuffer positionBuffer = MemoryUtil.memAllocFloat(vertices.length * 3); - float[] positionData = new float[vertices.length * 3]; - for (int i = 0; i < vertices.length; i++) { - positionData[i * 3] = vertices[i].x(); - positionData[i * 3 + 1] = vertices[i].y(); - positionData[i * 3 + 2] = vertices[i].z(); - } - positionBuffer.put(positionData).flip(); - - pbo = GL15.glGenBuffers(); - GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, pbo); - GL15.glBufferData(GL15.GL_ARRAY_BUFFER, positionBuffer, GL15.GL_STATIC_DRAW); - GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, 0, 0); - GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); - - IntBuffer indicesBuffer = MemoryUtil.memAllocInt(indices.length); - indicesBuffer.put(indices).flip(); - - ibo = GL15.glGenBuffers(); - GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, ibo); - GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, indicesBuffer, GL15.GL_STATIC_DRAW); - GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0); - } - - public Vertex3f[] getVertices() { - return vertices; - } - - public int[] getIndices() { - return indices; - } - - public int getVAO() { - return vao; - } - - public int getPBO() { - return pbo; - } - - public int getIBO() { - return ibo; - } -} diff --git a/src/pisi/unitedmeows/yystal/ui/utils/NullCheck.java b/src/pisi/unitedmeows/yystal/ui/utils/NullCheck.java deleted file mode 100644 index 9d04df7..0000000 --- a/src/pisi/unitedmeows/yystal/ui/utils/NullCheck.java +++ /dev/null @@ -1,17 +0,0 @@ -package pisi.unitedmeows.yystal.ui.utils; - -import org.lwjgl.system.MemoryUtil; - -public enum NullCheck { - CHECK; - - public boolean isNull(final Object object) { - if (object == null) return true; - if ((object instanceof Long) && ((Long) object == MemoryUtil.NULL)) return true; - if (object instanceof Rectangle) { - final Rectangle rectangle = (Rectangle) object; - if (rectangle.hashCode() == -1) return true; - } - return false; - } -} diff --git a/src/pisi/unitedmeows/yystal/ui/utils/Rectangle.java b/src/pisi/unitedmeows/yystal/ui/utils/Rectangle.java deleted file mode 100644 index aba2e64..0000000 --- a/src/pisi/unitedmeows/yystal/ui/utils/Rectangle.java +++ /dev/null @@ -1,68 +0,0 @@ -package pisi.unitedmeows.yystal.ui.utils; - - -import org.joml.Vector4f; - -import static org.lwjgl.opengl.GL11.GL_BLEND; -import static org.lwjgl.opengl.GL11.GL_FLAT; -import static org.lwjgl.opengl.GL11.GL_LINE_SMOOTH; -import static org.lwjgl.opengl.GL11.GL_ONE_MINUS_SRC_ALPHA; -import static org.lwjgl.opengl.GL11.GL_QUADS; -import static org.lwjgl.opengl.GL11.GL_SMOOTH; -import static org.lwjgl.opengl.GL11.GL_SRC_ALPHA; -import static org.lwjgl.opengl.GL11.GL_TEXTURE_2D; -import static org.lwjgl.opengl.GL11.glBegin; -import static org.lwjgl.opengl.GL11.glBlendFunc; -import static org.lwjgl.opengl.GL11.glColor4f; -import static org.lwjgl.opengl.GL11.glDisable; -import static org.lwjgl.opengl.GL11.glEnable; -import static org.lwjgl.opengl.GL11.glEnd; -import static org.lwjgl.opengl.GL11.glPopMatrix; -import static org.lwjgl.opengl.GL11.glPushMatrix; -import static org.lwjgl.opengl.GL11.glShadeModel; -import static org.lwjgl.opengl.GL11.glVertex2d; - - -public class Rectangle { - public Vector4f vector; - - public Rectangle(final Vector4f vector) { this.vector = vector; } - - public Rectangle(final float x, final float y, final float z, final float w) { this.vector = new Vector4f(x, y, z, w); } - - public Rectangle(final float[] xyzw) { this.vector = new Vector4f(xyzw[0], xyzw[1], xyzw[2], xyzw[3]); } - - public Rectangle expand(final float x, final float y, final float x2, final float y2) { - vector.x += x; - vector.y += y; - vector.z += x2; - vector.w += y2; - return this; - } - - public void draw(final int color) { draw(color, color); } - - // doesnt work at the moment :Dd - // gradient btw - public void draw(final int color, final int endColor) { - - //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glEnable(GL_LINE_SMOOTH); - glShadeModel(GL_SMOOTH); - glPushMatrix(); - glBegin(GL_QUADS); - glColor4f((color >> 16 & 255) / 255.0F, (color >> 8 & 255) / 255.0F, (color & 255) / 255.0F, (color >> 24 & 255) / 255.0F); - glVertex2d(vector.x, vector.y); - glVertex2d(vector.x, vector.w); - glColor4f((endColor >> 16 & 255) / 255.0F, (endColor >> 8 & 255) / 255.0F, (endColor & 255) / 255.0F, (endColor >> 24 & 255) / 255.0F); - glVertex2d(vector.z, vector.w); - glVertex2d(vector.z, vector.y); - glEnd(); - glPopMatrix(); - glDisable(GL_LINE_SMOOTH); - glShadeModel(GL_FLAT); - } - - @Override - public int hashCode() { return vector.hashCode(); } -} diff --git a/src/pisi/unitedmeows/yystal/ui/utils/Vertex2f.java b/src/pisi/unitedmeows/yystal/ui/utils/Vertex2f.java deleted file mode 100644 index 4fd0cd9..0000000 --- a/src/pisi/unitedmeows/yystal/ui/utils/Vertex2f.java +++ /dev/null @@ -1,25 +0,0 @@ -package pisi.unitedmeows.yystal.ui.utils; - -public class Vertex2f { - public float x, y; - public Vertex2f(float _x, float _y) { - x = _x; - y = _y; - } - - public float x() { - return x; - } - - public float y() { - return y; - } - - public void setX(float x) { - this.x = x; - } - - public void setY(float y) { - this.y = y; - } -} diff --git a/src/pisi/unitedmeows/yystal/ui/utils/Vertex3f.java b/src/pisi/unitedmeows/yystal/ui/utils/Vertex3f.java deleted file mode 100644 index 5b228ce..0000000 --- a/src/pisi/unitedmeows/yystal/ui/utils/Vertex3f.java +++ /dev/null @@ -1,35 +0,0 @@ -package pisi.unitedmeows.yystal.ui.utils; - -public class Vertex3f { - public float x, y, z; - - public Vertex3f(float _x, float _y, float _z) { - x = _x; - y = _y; - z = _z; - } - - public float x() { - return x; - } - - public float y() { - return y; - } - - public float z() { - return z; - } - - public void setX(float x) { - this.x = x; - } - - public void setY(float y) { - this.y = y; - } - - public void setZ(float z) { - this.z = z; - } -} diff --git a/src/pisi/unitedmeows/yystal/ui/utils/YOrigin.java b/src/pisi/unitedmeows/yystal/ui/utils/YOrigin.java deleted file mode 100644 index ffc8b7d..0000000 --- a/src/pisi/unitedmeows/yystal/ui/utils/YOrigin.java +++ /dev/null @@ -1,8 +0,0 @@ -package pisi.unitedmeows.yystal.ui.utils; - -public enum YOrigin { - TOP_LEFT, - TOP_RIGHT, - BOTTOM_LEFT, - BOTTOM_RIGHT; -} diff --git a/src/pisi/unitedmeows/yystal/utils/Capsule.java b/src/pisi/unitedmeows/yystal/utils/Capsule.java deleted file mode 100644 index b09655b..0000000 --- a/src/pisi/unitedmeows/yystal/utils/Capsule.java +++ /dev/null @@ -1,50 +0,0 @@ -package pisi.unitedmeows.yystal.utils; - -import pisi.unitedmeows.yystal.clazz.function; -import pisi.unitedmeows.yystal.parallel.IFunction; - -import java.util.HashMap; -import java.util.function.Consumer; -import java.util.function.Predicate; - -public class Capsule { - - protected final HashMap parameters; - - public static Capsule of(Pair... params) { - final Capsule capsule = new Capsule(params.length); - for (Pair param : params) { - capsule.parameters.put(param.item1(), param.item2()); - } - return capsule; - } - - protected Capsule(int paramCount) { - parameters = new HashMap<>(paramCount); - } - - public X get(String paramName) { - return (X) parameters.getOrDefault(paramName, null); - } - - public X getOrDefault(String paramName, X defaultVal) { - return (X) parameters.getOrDefault(paramName, defaultVal); - } - - public boolean contains(String paramName) { - return parameters.containsKey(paramName); - } - - public boolean exists() { - return !parameters.isEmpty(); - } - - public X ifExists(String paramName, Consumer func) { - X value = get(paramName); - if (value != null) { - func.accept(value); - } - return value; - } - -} diff --git a/src/pisi/unitedmeows/yystal/utils/CoID.java b/src/pisi/unitedmeows/yystal/utils/CoID.java deleted file mode 100644 index e4eb59e..0000000 --- a/src/pisi/unitedmeows/yystal/utils/CoID.java +++ /dev/null @@ -1,124 +0,0 @@ -package pisi.unitedmeows.yystal.utils; - -import java.util.Random; -import java.util.regex.Pattern; - -/** Complex IDentity */ -public class CoID implements Comparable { - - //SS$UDUD-LLD-SULUUULL-DD - public static final String ALL_UPPERCASE = "ABCDEFGHIJKLMNOPRSTUVYZXQ"; - public static final String DIGITS = "0123456789"; - public static final String ALL_LOWERCASE = "abcdefghijklmnoprstuvyzxq"; - public static final String SPECIAL_CHARS = "COMPLEX2173"; - private static final Pattern coidPattern = Pattern.compile("[COMPLEX2173]{2}\\$[A-Z][0-9][A-Z][0-9]\\-[a-z]{2}[0-9]\\-[COMPLEX2173][A-Z][a-z][A-Z]{3}[a-z]{2}\\-[0-9]{2}"); - private static Random random = new Random(); - private static final int COID_LENGTH = 23; - - private final String value; - - public CoID(String val) { - value = val; - } - - @Override - public String toString() { - return value; - } - - public static CoID generate() { - //SS$UDUD-LLD-SULUUULL-DD - StringBuilder builder = new StringBuilder(); - // SS - builder.append(nextSpecial()); // 11 - builder.append(nextSpecial()); // 11 - builder.append('$'); - - //UDUD - builder.append(nextUpper()); // 25 - builder.append(nextDigit()); // 10 - builder.append(nextUpper()); // 25 - builder.append(nextDigit()); // 10 - builder.append('-'); - - //LLD - builder.append(nextLower()); // 25 - builder.append(nextLower()); // 25 - builder.append(nextDigit()); // 10 - builder.append('-'); - - //SULUUULL - builder.append(nextSpecial()); // S 11 - builder.append(nextUpper()); // U 25 - builder.append(nextLower()); // L 11 - builder.append(nextUpper()); // U 25 - builder.append(nextUpper()); // U 25 - builder.append(nextUpper()); // U 25 - builder.append(nextLower()); // L 25 - builder.append(nextLower()); // L 25 - builder.append('-'); - //DD - builder.append(nextDigit()); // 10 - builder.append(nextDigit()); - return new CoID(builder.toString()); - - } - - private static char nextUpper() { - return ALL_UPPERCASE.charAt(random.nextInt(ALL_LOWERCASE.length())); - } - - private static char nextLower() { - return ALL_LOWERCASE.charAt(random.nextInt(ALL_LOWERCASE.length())); - } - - private static char nextSpecial() { - return SPECIAL_CHARS.charAt(random.nextInt(SPECIAL_CHARS.length())); - } - - private static char nextDigit() { - return DIGITS.charAt(random.nextInt(DIGITS.length())); - } - - - //TODO: Check for pattern - @Deprecated - public static boolean isLegal(String coid) { - if (coid.length() != 23) { - return false; - } - return coidPattern.matcher(coid).matches(); - } - - public static boolean isLegal(CoID coID) { - return isLegal(coID.toString()); - } - - - public static void setRandom(Random random) { - CoID.random = random; - } - - @Override - public int compareTo(CoID o) { - return toString().equals(o.toString()) ? 1 : 0; - } - - public boolean same(CoID o2) { - return toString().equals(o2.toString()); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - CoID coID = (CoID) o; - - return value != null ? value.equals(coID.value) : coID.value == null; - } - - @Override - public int hashCode() { - return value.hashCode(); - } -} \ No newline at end of file diff --git a/src/pisi/unitedmeows/yystal/utils/ImageUtils.java b/src/pisi/unitedmeows/yystal/utils/ImageUtils.java deleted file mode 100644 index 319e2a1..0000000 --- a/src/pisi/unitedmeows/yystal/utils/ImageUtils.java +++ /dev/null @@ -1,43 +0,0 @@ -package pisi.unitedmeows.yystal.utils; -import javax.imageio.ImageIO; -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -public class ImageUtils { - public static byte[] toByteArray(BufferedImage bi, ImageType type) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { - ImageIO.write(bi, type.type(), baos); - } catch (IOException e) { - return null; - } - return baos.toByteArray(); - - } - - public static BufferedImage toBufferedImage(byte[] bytes) { - try { - InputStream is = new ByteArrayInputStream(bytes); - return ImageIO.read(is); - } catch (IOException ex) { - return null; - } - } - - public enum ImageType { - PNG("png"), - JPG("jpg"), - GIF("gif"); /* todo: add more */ - String type; - ImageType(String type) { - this.type = type; - } - - public String type() { - return type; - } - } -} - diff --git a/src/pisi/unitedmeows/yystal/utils/Iterate.java b/src/pisi/unitedmeows/yystal/utils/Iterate.java deleted file mode 100644 index 77f1562..0000000 --- a/src/pisi/unitedmeows/yystal/utils/Iterate.java +++ /dev/null @@ -1,6 +0,0 @@ -package pisi.unitedmeows.yystal.utils; - -@FunctionalInterface -public interface Iterate { - public boolean next(X object); -} \ No newline at end of file diff --git a/src/pisi/unitedmeows/yystal/utils/MemoryReader.java b/src/pisi/unitedmeows/yystal/utils/MemoryReader.java deleted file mode 100644 index 01971f7..0000000 --- a/src/pisi/unitedmeows/yystal/utils/MemoryReader.java +++ /dev/null @@ -1,58 +0,0 @@ -package pisi.unitedmeows.yystal.utils; - - -import java.awt.image.BufferedImage; -import java.io.*; - -public class MemoryReader extends DataInputStream { - - private ByteArrayInputStream inputStream; - - public MemoryReader(byte[] data) { - super(null); - inputStream = new ByteArrayInputStream(data); - in = inputStream; - } - - public String readString() { - try { - return super.readUTF(); - } catch (IOException e) { - return null; - } - } - - @Override - public int read() { - try { - return super.read(); - } catch (Exception ex){ - return -1; - } - } - - - - public BufferedImage readImage() { - try { - int length = readInt(); - byte[] bytes = new byte[length]; - read(bytes); - return ImageUtils.toBufferedImage(bytes); - } catch (IOException e) { - return null; - } - } - - public byte[] getBytes() { - byte[] array = new byte[inputStream.available()]; - try { - inputStream.read(array); - - return array; - } catch (IOException e) { - return null; - } - } - -} diff --git a/src/pisi/unitedmeows/yystal/utils/MemoryWriter.java b/src/pisi/unitedmeows/yystal/utils/MemoryWriter.java deleted file mode 100644 index d545127..0000000 --- a/src/pisi/unitedmeows/yystal/utils/MemoryWriter.java +++ /dev/null @@ -1,30 +0,0 @@ -package pisi.unitedmeows.yystal.utils; - -import java.io.ByteArrayOutputStream; -import java.awt.image.BufferedImage; -import java.io.*; -public class MemoryWriter extends DataOutputStream { - - private ByteArrayOutputStream outputStream; - - public MemoryWriter() { - super(null); - outputStream = new ByteArrayOutputStream(); - out = outputStream; - } - - public byte[] getBytes() { - return outputStream.toByteArray(); - } - - public void writeImage(BufferedImage image, ImageUtils.ImageType type) { - byte[] data = ImageUtils.toByteArray(image, type); - try { - write(data.length); - - write(data); - } catch (IOException e) { - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/src/pisi/unitedmeows/yystal/utils/Pair.java b/src/pisi/unitedmeows/yystal/utils/Pair.java deleted file mode 100644 index b5d2096..0000000 --- a/src/pisi/unitedmeows/yystal/utils/Pair.java +++ /dev/null @@ -1,21 +0,0 @@ -package pisi.unitedmeows.yystal.utils; - -public class Pair { - - private F item1; - private S item2; - - public Pair(F _item1, S _item2) { - item1 = _item1; - item2 = _item2; - } - - public F item1() { - return item1; - } - - public S item2() { - return item2; - } - -} diff --git a/src/pisi/unitedmeows/yystal/utils/Stopwatch.java b/src/pisi/unitedmeows/yystal/utils/Stopwatch.java deleted file mode 100644 index 4b94e2f..0000000 --- a/src/pisi/unitedmeows/yystal/utils/Stopwatch.java +++ /dev/null @@ -1,35 +0,0 @@ -package pisi.unitedmeows.yystal.utils; - -public class Stopwatch { - - private long ms; - - public Stopwatch() { - reset(); - } - - public boolean isReached(long milliseconds) { - return getTime() - ms >= milliseconds; - } - - private long getTime() - { - return System.nanoTime() / 1000000L; - } - - public void reset() - { - this.ms = getTime(); - } - - public Stopwatch resetBack(long time) { - this.ms = getTime() - time; - return this; - } - - public long elapsed() - { - return getTime() - ms; - } - -} diff --git a/src/pisi/unitedmeows/yystal/utils/Types.java b/src/pisi/unitedmeows/yystal/utils/Types.java deleted file mode 100644 index ef092f7..0000000 --- a/src/pisi/unitedmeows/yystal/utils/Types.java +++ /dev/null @@ -1,24 +0,0 @@ -package pisi.unitedmeows.yystal.utils; - -import java.util.HashMap; - -public class Types { - - protected static HashMap, Integer> typeLengths; - - static { - typeLengths = new HashMap, Integer>() {{ - put(Integer.class, 4); - put(Byte.class, 1); - put(Long.class, 8); - put(Short.class, 2); - put(Boolean.class, 1); - put(Double.class, 8); - put(Character.class, 2); - }}; - } - - public static int sizeof(Class clazz) { - return typeLengths.getOrDefault(clazz, 0); - } -} diff --git a/src/pisi/unitedmeows/yystal/utils/Vector2.java b/src/pisi/unitedmeows/yystal/utils/Vector2.java deleted file mode 100644 index 11a1dd6..0000000 --- a/src/pisi/unitedmeows/yystal/utils/Vector2.java +++ /dev/null @@ -1,19 +0,0 @@ -package pisi.unitedmeows.yystal.utils; - -public class Vector2 { - private F first; - private S second; - - public Vector2(final F first, final S second) { - this.first = first; - this.second = second; - } - - public F setX(final F val) { return this.first = val; } - - public F getX() { return first; } - - public S getY() { return second; } - - public S setY(final S val) { return this.second = val; } -} diff --git a/src/pisi/unitedmeows/yystal/utils/Vector2f.java b/src/pisi/unitedmeows/yystal/utils/Vector2f.java deleted file mode 100644 index c8965b6..0000000 --- a/src/pisi/unitedmeows/yystal/utils/Vector2f.java +++ /dev/null @@ -1,9 +0,0 @@ -package pisi.unitedmeows.yystal.utils; - - -public class Vector2f extends Vector2 { - - public Vector2f(float first, float second) { - super(first, second); - } -} diff --git a/src/pisi/unitedmeows/yystal/utils/Vector3.java b/src/pisi/unitedmeows/yystal/utils/Vector3.java deleted file mode 100644 index 865a0f5..0000000 --- a/src/pisi/unitedmeows/yystal/utils/Vector3.java +++ /dev/null @@ -1,26 +0,0 @@ -package pisi.unitedmeows.yystal.utils; - -public class Vector3 { - - private F first; - private S second; - private T third; - - public Vector3(F _first, S _second, T _third) { - first = _first; - second = _second; - third = _third; - } - - public F first() { - return first; - } - - public S second() { - return second; - } - - public T third() { - return third; - } -} diff --git a/src/pisi/unitedmeows/yystal/utils/Vector4f.java b/src/pisi/unitedmeows/yystal/utils/Vector4f.java deleted file mode 100644 index ccb638b..0000000 --- a/src/pisi/unitedmeows/yystal/utils/Vector4f.java +++ /dev/null @@ -1,4 +0,0 @@ -package pisi.unitedmeows.yystal.utils; - -public class Vector4f { -} diff --git a/src/pisi/unitedmeows/yystal/utils/YRandom.java b/src/pisi/unitedmeows/yystal/utils/YRandom.java deleted file mode 100644 index 5bb2d0b..0000000 --- a/src/pisi/unitedmeows/yystal/utils/YRandom.java +++ /dev/null @@ -1,32 +0,0 @@ -package pisi.unitedmeows.yystal.utils; - -import java.util.Random; - -public class YRandom { - public static final YRandom BASIC = new YRandom(); - private final Random random; - - public YRandom() { - random = new Random(); - } - - public int nextInRange(int min, int max) { - return random.nextInt(max - min) + min; - } - - public byte nextByte() { - return (byte) nextInRange(-127, 127); - } - - public byte nextByte(int min, int max) { - return (byte) nextInRange(min, max); - } - - public int nextInt() { - return random.nextInt(); - } - - public int nextInt(int max) { - return random.nextInt(max); - } -} diff --git a/src/pisi/unitedmeows/yystal/utils/kThread.java b/src/pisi/unitedmeows/yystal/utils/kThread.java deleted file mode 100644 index c4f5cbd..0000000 --- a/src/pisi/unitedmeows/yystal/utils/kThread.java +++ /dev/null @@ -1,26 +0,0 @@ -package pisi.unitedmeows.yystal.utils; - -import pisi.unitedmeows.yystal.parallel.IState; - -public class kThread { - - public static void sleep(long time) { - try { - Thread.sleep(time); - } catch (InterruptedException e) { - - } - } - - public static void sleep_till(IState state) { - while (state.check()) { - sleep(1); - } - } - - public static void sleep_untill(IState state) { - while (!state.check()) { - sleep(1); - } - } -} diff --git a/src/pisi/unitedmeows/yystal/web/YWebClient.java b/src/pisi/unitedmeows/yystal/web/YWebClient.java deleted file mode 100644 index fd0cc25..0000000 --- a/src/pisi/unitedmeows/yystal/web/YWebClient.java +++ /dev/null @@ -1,522 +0,0 @@ -package pisi.unitedmeows.yystal.web; - -import pisi.unitedmeows.yystal.YYStal; -import pisi.unitedmeows.yystal.clazz.event; -import pisi.unitedmeows.yystal.clazz.out; -import pisi.unitedmeows.yystal.hook.YString; -import pisi.unitedmeows.yystal.utils.YRandom; -import pisi.unitedmeows.yystal.web.events.WCDownloadFinished; -import pisi.unitedmeows.yystal.web.events.WCDownloadProgress; - -import java.io.*; -import java.net.*; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.StringJoiner; -import java.util.stream.Collectors; - -public class YWebClient { - - private int timeout = 10000; - private Map headers = createDefaultHeaders(); - private static final String DEFAULT_USER_AGENT = randomUserAgent(); - private Map> responseHeaders = new HashMap<>(); - - /* Download Progress Event only works when server has set Content-Length header - * otherwise the only correct value will be currentBytes variable */ - public event downloadProgressEvent = new event<>(); - public event downloadFinishedEvent = new event<>(); - - - public String downloadString(String url) { - try { - return downloadString(new URL(url)); - } catch (MalformedURLException e) { - return null; - } - } - - public byte[] downloadBytes(String url) { - try { - return downloadBytes(new URL(url)); - } catch (MalformedURLException e) { - return null; - } - } - - public byte[] downloadBytes(URL url) { - try { - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setReadTimeout(timeout); - connection.setConnectTimeout(timeout); - - /* sets default headers */ - headers.forEach(connection::addRequestProperty); - - /* tries to connect the webserver */ - connection.connect(); - - out newUrl = YYStal.out(); - if (redirectCheck(connection, newUrl)) { - return downloadBytes(newUrl.get()); - } - - final int contentLength = connection.getContentLength(); - int count; - downloadProgressEvent.fire(0, 0, contentLength); - byte data[] = new byte[4096]; - try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()){ - while ((count = connection.getInputStream().read(data)) != -1) { - outputStream.write(data, 0, count); - double percent = (outputStream.size() * 100D) / contentLength; - downloadProgressEvent.fire(percent, outputStream.size(), contentLength); - } - responseHeaders = connection.getHeaderFields(); - - byte[] result = outputStream.toByteArray(); - downloadFinishedEvent.fire(); - return result; - } - - - } catch (Exception e) { - return null; - } - } - - public boolean downloadFile(String url, File file) { - try { - return downloadFile(new URL(url), file); - } catch (MalformedURLException e) { - return false; - } - } - - - - public boolean downloadFile(URL url, File file) { - try { - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setReadTimeout(timeout); - connection.setConnectTimeout(timeout); - - /* sets default headers */ - headers.forEach(connection::addRequestProperty); - - /* tries to connect the webserver */ - connection.connect(); - - out newUrl = YYStal.out(); - if (redirectCheck(connection, newUrl)) { - return downloadFile(newUrl.get(), file); - } - - int count; - - byte data[] = new byte[4096]; - final int contentLength = connection.getContentLength(); - int totalDownloaded = 0; - downloadProgressEvent.fire(0, 0, contentLength); - try (FileOutputStream outputStream = new FileOutputStream(file)){ - while ((count = connection.getInputStream().read(data)) != -1) { - outputStream.write(data, 0, count); - totalDownloaded += count; - downloadProgressEvent.fire((totalDownloaded * 100) / contentLength, totalDownloaded, contentLength); - outputStream.flush(); - } - outputStream.flush(); - downloadFinishedEvent.fire(); - responseHeaders = connection.getHeaderFields(); - } - - return true; - } catch (Exception e) { - return false; - } - } - - public String downloadString(URL url) { - try { - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setReadTimeout(timeout); - connection.setConnectTimeout(timeout); - - /* sets default headers */ - headers.forEach(connection::addRequestProperty); - - /* tries to connect the webserver */ - connection.connect(); - - out newUrl = YYStal.out(); - if (redirectCheck(connection, newUrl)) { - return downloadString(newUrl.get()); - } - responseHeaders = connection.getHeaderFields(); - try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) { - return reader.lines().collect(Collectors.joining("\n")); - } - - } catch (Exception e) { - return null; - } - } - - - - public String postRequest(String url, Map args, String contentType) { - try { - return postRequest(new URL(url), args, contentType); - } catch (MalformedURLException e) { - return null; - } - } - - public String postRequest(URL url, Map args) { - return postRequest(url, args, "text/html"); - } - - public String postRequest(String url, Map args) { - try { - return postRequest(new URL(url), args, "text/html"); - } catch (Exception ex) { - return null; - } - } - - public String postRequest(URL url, Map args, String contentType) { - - try { - StringJoiner stringJoiner = new StringJoiner("&"); - for (Map.Entry entry : args.entrySet()) - stringJoiner.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8")); - - return postRequest(url, stringJoiner.toString(), contentType); - } catch (Exception ex) { - return null; - } - } - - public String postRequest(String url, String value, String contentType) { - try { - return postRequest(new URL(url), value, contentType); - } catch (MalformedURLException e) { - return null; - } - } - - public String postRequest(String url, String value) { - try { - return postRequest(new URL(url), value, "application/json"); - } catch (MalformedURLException e) { - return null; - } - } - - - public String postRequest(URL url, String value, String contentType) { - try { - URLConnection connection = url.openConnection(); - - /* setup http connection */ - HttpURLConnection http = (HttpURLConnection) connection; - http.setRequestMethod("POST"); - http.setDoOutput(true); - - /* add headers */ - headers.forEach(connection::addRequestProperty); - - - - byte[] out = value.getBytes(StandardCharsets.UTF_8); - int length = out.length; - http.setFixedLengthStreamingMode(length); - http.setRequestProperty("Content-Type", contentType); - http.setRequestProperty("charset", "utf-8"); - http.setRequestProperty("Content-Length", Integer.toString( length )); - http.setInstanceFollowRedirects( false ); - http.setUseCaches( false ); - http.connect(); - - - - try(OutputStream os = http.getOutputStream()) { - os.write(out); - } - /* check for redirects */ - out newUrl = YYStal.out(); - if (redirectCheck(http, newUrl)) { - return postRequest(newUrl.get(), value, contentType); - } - - responseHeaders = connection.getHeaderFields(); - StringBuilder stringBuilder = new StringBuilder(); - if (http.getResponseCode() == HttpURLConnection.HTTP_OK) { - try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(http.getInputStream()))) { - String line; - while ((line = bufferedReader.readLine()) != null) { - stringBuilder.append(line); - } - } - } else if (http.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) { - return ""; - }else { - return null; - } - return stringBuilder.toString(); - - } catch (Exception ex) { - return null; - } - } - - public String putRequest(String url, String value) { - return putRequest(url, value, "application/json"); - } - - public String putRequest(String url, String value, String contentType) { - try { - return putRequest(new URL(url), value, contentType); - } catch (MalformedURLException ex) { - return null; - } - } - - public String putRequest(URL url, String value) { - return putRequest(url, value, "application/json"); - } - - public String putRequest(URL url, String value, String contentType) { - try { - URLConnection connection = url.openConnection(); - - /* setup http connection */ - HttpURLConnection http = (HttpURLConnection) connection; - http.setRequestMethod("PUT"); - http.setDoOutput(true); - - /* add headers */ - headers.forEach(connection::addRequestProperty); - - - - byte[] out = value.getBytes(StandardCharsets.UTF_8); - int length = out.length; - http.setFixedLengthStreamingMode(length); - http.setRequestProperty("Content-Type", contentType); - http.setRequestProperty("charset", "utf-8"); - http.setRequestProperty("Content-Length", Integer.toString( length )); - http.setInstanceFollowRedirects( false ); - http.setUseCaches( false ); - http.connect(); - - - - try(OutputStream os = http.getOutputStream()) { - os.write(out); - } - /* check for redirects */ - out newUrl = YYStal.out(); - if (redirectCheck(http, newUrl)) { - return postRequest(newUrl.get(), value, contentType); - } - - responseHeaders = connection.getHeaderFields(); - StringBuilder stringBuilder = new StringBuilder(); - if (http.getResponseCode() == HttpURLConnection.HTTP_OK) { - try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(http.getInputStream()))) { - String line; - while ((line = bufferedReader.readLine()) != null) { - stringBuilder.append(line); - } - } - } else if (http.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) { - return ""; - }else { - return null; - } - return stringBuilder.toString(); - - } catch (Exception ex) { - return null; - } - } - public String patchRequest(String url, String value) { - return patchRequest(url, value, "application/json"); - } - - public String patchRequest(String url, String value, String contentType) { - try { - return patchRequest(new URL(url), value, contentType); - } catch (MalformedURLException ex) { - return null; - } - } - - public String patchRequest(URL url, String value) { - return patchRequest(url, value, "application/json"); - } - - public String patchRequest(URL url, String value, String contentType) { - try { - URLConnection connection = url.openConnection(); - - /* setup http connection */ - HttpURLConnection http = (HttpURLConnection) connection; - http.setRequestMethod("PATCH"); - http.setDoOutput(true); - - /* add headers */ - headers.forEach(connection::addRequestProperty); - - - - byte[] out = value.getBytes(StandardCharsets.UTF_8); - int length = out.length; - http.setFixedLengthStreamingMode(length); - http.setRequestProperty("Content-Type", contentType); - http.setRequestProperty("charset", "utf-8"); - http.setRequestProperty("Content-Length", Integer.toString( length )); - http.setInstanceFollowRedirects( false ); - http.setUseCaches( false ); - http.connect(); - - - - try(OutputStream os = http.getOutputStream()) { - os.write(out); - } - /* check for redirects */ - out newUrl = YYStal.out(); - if (redirectCheck(http, newUrl)) { - return postRequest(newUrl.get(), value, contentType); - } - - responseHeaders = connection.getHeaderFields(); - StringBuilder stringBuilder = new StringBuilder(); - if (http.getResponseCode() == HttpURLConnection.HTTP_OK) { - try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(http.getInputStream()))) { - String line; - while ((line = bufferedReader.readLine()) != null) { - stringBuilder.append(line); - } - } - } else if (http.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) { - return ""; - }else { - return null; - } - return stringBuilder.toString(); - - } catch (Exception ex) { - return null; - } - } - - - public String deleteRequest(URL url) { - try { - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setReadTimeout(timeout); - connection.setConnectTimeout(timeout); - connection.setRequestMethod("DELETE"); - - /* sets default headers */ - headers.forEach(connection::addRequestProperty); - - /* tries to connect the webserver */ - connection.connect(); - - out newUrl = YYStal.out(); - if (redirectCheck(connection, newUrl)) { - return downloadString(newUrl.get()); - } - responseHeaders = connection.getHeaderFields(); - try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) { - return reader.lines().collect(Collectors.joining("\n")); - } - - } catch (Exception e) { - return null; - } - } - - public String deleteRequest(String url) { - try { - return deleteRequest(new URL(url)); - } catch (MalformedURLException ex) { - return null; - } - } - - - public static boolean redirectCheck(HttpURLConnection connection, out url) { - try { - int responseCode = connection.getResponseCode(); - - if (responseCode < 400 && responseCode >= 300) { - String redirectUrl = connection.getHeaderField("Location"); - try { - url.set(new URL(redirectUrl)); - } catch (Exception ex) { - URL newUrl = new URL(connection.getURL().getProtocol() + "://" + connection.getURL().getHost() + redirectUrl); - url.set(newUrl); - } - return true; - } - } catch (Exception ex) {} - - return false; - } - - public Map> responseHeaders() { - return responseHeaders; - } - - public void cookie(String cookies) { - headers.put("Cookie", cookies); - } - - public void appendCookie(String cookie) { - headers.put("Cookie", headers.getOrDefault("Cookie", YString.EMPTY_R) + cookie); - } - - private static Map createDefaultHeaders() { - HashMap headers = new HashMap<>(); - headers.put("User-Agent", DEFAULT_USER_AGENT); - - return headers; - } - - public YWebClient setUserAgent(String userAgent) { - headers.put("User-Agent", userAgent); - return this; - } - - private static String randomUserAgent() { - String[] userAgents = new String[]{ - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_3; rv:95.0) Gecko/20010101 Firefox/95.0", - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4667.82 Safari/537.36", - "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20110101 Firefox/93.0", - "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4648.150 Safari/537.36", - "Mozilla/5.0 (X11; U; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4655.89 Safari/537.36", - "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4692.110 Safari/537.36", - "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4661.55 Safari/537.36", - "Mozilla/5.0 (Windows NT 11.0; Win64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4641.165 Safari/537.36", - "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.174 Safari/537.36" - }; - return userAgents[YRandom.BASIC.nextInt(userAgents.length)]; - } - - - public YWebClient setTimeout(int timeout) { - this.timeout = timeout; - return this; - } - - public YWebClient header(String header, String value) { - headers.put(header, value); - return this; - } -} diff --git a/src/pisi/unitedmeows/yystal/web/events/WCDownloadFinished.java b/src/pisi/unitedmeows/yystal/web/events/WCDownloadFinished.java deleted file mode 100644 index d57f9c3..0000000 --- a/src/pisi/unitedmeows/yystal/web/events/WCDownloadFinished.java +++ /dev/null @@ -1,7 +0,0 @@ -package pisi.unitedmeows.yystal.web.events; - -import pisi.unitedmeows.yystal.clazz.delegate; - -public interface WCDownloadFinished extends delegate { - public void onDownloadFinished(); -} diff --git a/src/pisi/unitedmeows/yystal/web/events/WCDownloadProgress.java b/src/pisi/unitedmeows/yystal/web/events/WCDownloadProgress.java deleted file mode 100644 index 364bfe6..0000000 --- a/src/pisi/unitedmeows/yystal/web/events/WCDownloadProgress.java +++ /dev/null @@ -1,11 +0,0 @@ -package pisi.unitedmeows.yystal.web.events; - -import pisi.unitedmeows.yystal.clazz.delegate; - -/* Download Progress Event only works when server has set Content-Length header - * otherwise the only correct value will be currentBytes variable */ -@Deprecated -public interface WCDownloadProgress extends delegate { - @Deprecated - public void onProgress(double percent, long currentBytes, long totalBytes); -} diff --git a/src/pisi/unitedmeows/yystal/yap/YAppServer.java b/src/pisi/unitedmeows/yystal/yap/YAppServer.java deleted file mode 100644 index 95b6c63..0000000 --- a/src/pisi/unitedmeows/yystal/yap/YAppServer.java +++ /dev/null @@ -1,109 +0,0 @@ -package pisi.unitedmeows.yystal.yap; - -import pisi.unitedmeows.yystal.clazz.event; -import pisi.unitedmeows.yystal.networking.IPAddress; -import pisi.unitedmeows.yystal.networking.events.SDataReceivedEvent; -import pisi.unitedmeows.yystal.networking.server.YSocketClient; -import pisi.unitedmeows.yystal.networking.server.YTcpServer; -import pisi.unitedmeows.yystal.utils.CoID; -import pisi.unitedmeows.yystal.utils.MemoryReader; -import pisi.unitedmeows.yystal.yap.events.YSSignalReceived; -import stelix.xfile.SxfDataBlock; -import stelix.xfile.SxfFile; -import stelix.xfile.writer.SxfWriter; - -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.ServerSocket; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; - -public class YAppServer { - - protected YTcpServer tcpServer; - private String appName; - private double appVersion; - private CoID appId; - private final String introductionMessage; - public event signalReceivedEvent = new event<>(); - - public YAppServer(String _appName, double _appVersion, CoID _appId, final IPAddress address, final int port) { - appName = _appName; - appVersion = _appVersion; - appId = _appId; - introductionMessage = createAppIntroduction(); - tcpServer = new YTcpServer(address, port); - } - - public YAppServer(String _appName, double _appVersion, CoID _appId, final int port) { - this(_appName, _appVersion, _appId, IPAddress.LOOPBACK, port); - } - - public YAppServer(String _appName, double _appVersion, CoID _appId) { - this(_appName, _appVersion, _appId, findAvailablePort()); - } - - public int port() { - return tcpServer.port(); - } - - public YapSignalBuilder newSignal() { - return YapSignalBuilder.builder(); - } - - public void listen() { - tcpServer.makeFixed(); - tcpServer.listen(); - - tcpServer.dataReceiveEvent.bind(new SDataReceivedEvent() { - @Override - public void onClientDataReceived(YSocketClient client, byte[] data) { - if (Arrays.equals(data, YapConstants.ASK_INTRODUCTION.data())) { - client.write(introductionMessage.getBytes(StandardCharsets.UTF_8)); - } else { - signalReceivedEvent.fire(client, new YapSignal(new MemoryReader(data))); - } - } - }); - } - - - - protected static int findAvailablePort() { - String osName = System.getProperty("os.name").toLowerCase(); - boolean isMacOs = osName.startsWith("mac os x"); - for (int port = 3217; port < 3217 + 30; port++) { - if (isAvailablePort(port, isMacOs)) { - return port; - } - } - return -1; - } - - protected String createAppIntroduction() { - SxfFile file = new SxfFile(); - SxfDataBlock app = new SxfDataBlock(); - app.putVar("name", appName); - app.putVar("version", appVersion); - app.putVar("id", appId.toString()); - file.put("app", app); - SxfWriter sxfWriter = new SxfWriter(); - sxfWriter.setWriteType(SxfWriter.WriteType.INLINE); - return sxfWriter.writeToString(file); - } - - protected static boolean isAvailablePort(int port, boolean isMac) { - try (ServerSocket serverSocket = new ServerSocket()) { - if (isMac) { - serverSocket.setReuseAddress(false); - } - serverSocket.bind(new InetSocketAddress(InetAddress.getByName("localhost"), port), 1); - } catch (Exception ex) { - return false; - } - return true; - } - public YTcpServer tcpServer() { - return tcpServer; - } -} diff --git a/src/pisi/unitedmeows/yystal/yap/YapClient.java b/src/pisi/unitedmeows/yystal/yap/YapClient.java deleted file mode 100644 index bdb7d56..0000000 --- a/src/pisi/unitedmeows/yystal/yap/YapClient.java +++ /dev/null @@ -1,53 +0,0 @@ -package pisi.unitedmeows.yystal.yap; - -import pisi.unitedmeows.yystal.clazz.event; -import pisi.unitedmeows.yystal.networking.IPAddress; -import pisi.unitedmeows.yystal.networking.client.YTcpClient; -import pisi.unitedmeows.yystal.networking.events.CDataReceivedEvent; -import pisi.unitedmeows.yystal.utils.MemoryReader; -import pisi.unitedmeows.yystal.yap.events.YCSignalReceived; - -public class YapClient { - - private YTcpClient tcpClient; - public event signalReceivedEvent = new event<>(); - - public YapClient(YTcpClient client) { - tcpClient = client; - tcpClient.dataReceivedEvent.bind(new CDataReceivedEvent() { - @Override - public void onDataReceived(byte[] data) { - signalReceivedEvent.fire(new YapSignal(new MemoryReader(data))); - } - }); - } - - public void connect(IPAddress address, int port) { - tcpClient.connect(address, port); - } - - - public YTcpClient tcpClient() { - return tcpClient; - } - - public YapSignalBuilder newSignal() { - return YapSignalBuilder.builder(); - } - - public void send(YapSignal signal) { - System.out.println("writing data"); - tcpClient.send(signal.reader().getBytes()); - } - - public void send(YapSignalBuilder builder) { - System.out.println("writing data"); - tcpClient.send(builder.buildBytes()); - } - - public YapClient() { - this(new YTcpClient().makeFixed()); - } - - -} diff --git a/src/pisi/unitedmeows/yystal/yap/YapConstants.java b/src/pisi/unitedmeows/yystal/yap/YapConstants.java deleted file mode 100644 index 41180c6..0000000 --- a/src/pisi/unitedmeows/yystal/yap/YapConstants.java +++ /dev/null @@ -1,17 +0,0 @@ -package pisi.unitedmeows.yystal.yap; - -import java.nio.charset.StandardCharsets; - -public enum YapConstants { - - ASK_INTRODUCTION(";;YAP_ASK_INTRODUCTION".getBytes(StandardCharsets.UTF_8)); - - private byte[] data; - YapConstants(byte[] _data) { - data = _data; - } - - public byte[] data() { - return data; - } -} diff --git a/src/pisi/unitedmeows/yystal/yap/YapSignal.java b/src/pisi/unitedmeows/yystal/yap/YapSignal.java deleted file mode 100644 index 4acb381..0000000 --- a/src/pisi/unitedmeows/yystal/yap/YapSignal.java +++ /dev/null @@ -1,22 +0,0 @@ -package pisi.unitedmeows.yystal.yap; - -import pisi.unitedmeows.yystal.clazz.HookClass; -import pisi.unitedmeows.yystal.utils.MemoryReader; -import pisi.unitedmeows.yystal.utils.MemoryWriter; - -public class YapSignal extends HookClass { - - public YapSignal() {} - - public YapSignal(MemoryReader memoryReader) { - hooked = memoryReader; - } - - public MemoryReader reader() { - return super.getHooked(); - } - - public byte[] data() { - return reader().getBytes(); - } -} diff --git a/src/pisi/unitedmeows/yystal/yap/YapSignalBuilder.java b/src/pisi/unitedmeows/yystal/yap/YapSignalBuilder.java deleted file mode 100644 index 8b20952..0000000 --- a/src/pisi/unitedmeows/yystal/yap/YapSignalBuilder.java +++ /dev/null @@ -1,87 +0,0 @@ -package pisi.unitedmeows.yystal.yap; - -import pisi.unitedmeows.yystal.clazz.HookClass; -import pisi.unitedmeows.yystal.utils.MemoryReader; -import pisi.unitedmeows.yystal.utils.MemoryWriter; - -import java.io.IOException; - -public class YapSignalBuilder extends HookClass { - - public YapSignalBuilder() { - hooked = new MemoryWriter(); - } - - public YapSignalBuilder write(int data) { - try { - hooked.writeInt(data); - } catch (IOException e) {} - return this; - } - - public YapSignalBuilder write(String data) { - try { - hooked.writeUTF(data); - } catch (IOException e) {} - return this; - } - - public YapSignalBuilder write(float data) { - try { - hooked.writeFloat(data); - } catch (IOException e) {} - return this; - } - - public YapSignalBuilder write(byte data) { - try { - hooked.writeByte(data); - } catch (IOException e) {} - return this; - } - - public YapSignalBuilder write(char data) { - try { - hooked.writeChar(data); - } catch (IOException e) {} - return this; - } - - public YapSignalBuilder write(short data) { - try { - hooked.writeShort(data); - } catch (IOException e) {} - return this; - } - - public YapSignalBuilder write(boolean data) { - try { - hooked.writeBoolean(data); - } catch (IOException e) {} - return this; - } - - public YapSignalBuilder write(byte[] data) { - try { - hooked.write(data); - } catch (IOException e) {} - return this; - } - - public YapSignalBuilder write(double data) { - try { - hooked.writeDouble(data); - } catch (IOException e) {} - return this; - } - - public static YapSignalBuilder builder() { - return new YapSignalBuilder(); - } - - public YapSignal build() { - return new YapSignal(new MemoryReader(getHooked().getBytes())); - } - public byte[] buildBytes() { return getHooked().getBytes(); } - -} \ No newline at end of file diff --git a/src/pisi/unitedmeows/yystal/yap/events/YCSignalReceived.java b/src/pisi/unitedmeows/yystal/yap/events/YCSignalReceived.java deleted file mode 100644 index b6a7f9e..0000000 --- a/src/pisi/unitedmeows/yystal/yap/events/YCSignalReceived.java +++ /dev/null @@ -1,8 +0,0 @@ -package pisi.unitedmeows.yystal.yap.events; - -import pisi.unitedmeows.yystal.clazz.delegate; -import pisi.unitedmeows.yystal.yap.YapSignal; - -public interface YCSignalReceived extends delegate { - public void onDataReceived(YapSignal signal); -} diff --git a/src/pisi/unitedmeows/yystal/yap/events/YSSignalReceived.java b/src/pisi/unitedmeows/yystal/yap/events/YSSignalReceived.java deleted file mode 100644 index f1cfb92..0000000 --- a/src/pisi/unitedmeows/yystal/yap/events/YSSignalReceived.java +++ /dev/null @@ -1,9 +0,0 @@ -package pisi.unitedmeows.yystal.yap.events; - -import pisi.unitedmeows.yystal.clazz.delegate; -import pisi.unitedmeows.yystal.networking.server.YSocketClient; -import pisi.unitedmeows.yystal.yap.YapSignal; - -public interface YSSignalReceived extends delegate { - public void onSignalReceived(YSocketClient socketClient, YapSignal signal); -} diff --git a/src/test/yystal/YTestStart.java b/src/test/yystal/YTestStart.java deleted file mode 100644 index 82dcb50..0000000 --- a/src/test/yystal/YTestStart.java +++ /dev/null @@ -1,77 +0,0 @@ -package test.yystal; - -import pisi.unitedmeows.yystal.YYStal; -import pisi.unitedmeows.yystal.exception.impl.YexIO; -import pisi.unitedmeows.yystal.file.YFile; -import pisi.unitedmeows.yystal.networking.IPAddress; -import pisi.unitedmeows.yystal.networking.client.YTcpClient; -import pisi.unitedmeows.yystal.networking.server.YTcpServer; -import pisi.unitedmeows.yystal.utils.Capsule; -import pisi.unitedmeows.yystal.utils.CoID; -import pisi.unitedmeows.yystal.utils.YRandom; -import pisi.unitedmeows.yystal.utils.kThread; -import pisi.unitedmeows.yystal.web.YWebClient; - - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static pisi.unitedmeows.yystal.parallel.Async.*; -import static pisi.unitedmeows.yystal.YYStal.*; - -public enum YTestStart { - gaming; /* :D */ - - public static void main(final String[] args) { - System.out.println("Starting.."); - System.out.println("============================="); - int i = 100; - long firstCheck; - - startWatcher(); - - { - YTcpServer server = new YTcpServer(IPAddress.LOOPBACK, 2173); - server.listen(); - YTcpClient client = new YTcpClient(); - while (i > 0) { - client.send(("hello world " + YRandom.BASIC.nextInt(9999)).getBytes(StandardCharsets.UTF_8)); - i--; - kThread.sleep(50); - } - client.close(); - server.close(); - } - - firstCheck = stopWatcher() - 50 * 100 /* remove the amount of time we sleep */; - - - System.out.println("Sending random bytes took " + firstCheck + "ms"); - - startWatcher(); - int massConnectClientSize = 40; - { - YTcpServer server = new YTcpServer(IPAddress.LOOPBACK, 2173); - server.listen(); - for (int j = massConnectClientSize; j > 0; j--) { - YTcpClient client = new YTcpClient(); - client.connect(IPAddress.LOOPBACK, 2173); - client.send("yystal".getBytes(StandardCharsets.UTF_8)); - kThread.sleep(50); - } - } - long secondCheck = stopWatcher() - massConnectClientSize * 50; /* remove the amount of time we sleep */; - System.out.println("Mass connect check took: (" + massConnectClientSize + " clients) " + secondCheck + "ms"); - System.out.println("============================="); - kThread.sleep(1099900); - } - - -} \ No newline at end of file diff --git a/test/yystal/YTestStart.java b/test/yystal/YTestStart.java index 9c5d465..82dcb50 100644 --- a/test/yystal/YTestStart.java +++ b/test/yystal/YTestStart.java @@ -3,6 +3,9 @@ import pisi.unitedmeows.yystal.YYStal; import pisi.unitedmeows.yystal.exception.impl.YexIO; import pisi.unitedmeows.yystal.file.YFile; +import pisi.unitedmeows.yystal.networking.IPAddress; +import pisi.unitedmeows.yystal.networking.client.YTcpClient; +import pisi.unitedmeows.yystal.networking.server.YTcpServer; import pisi.unitedmeows.yystal.utils.Capsule; import pisi.unitedmeows.yystal.utils.CoID; import pisi.unitedmeows.yystal.utils.YRandom; @@ -14,6 +17,7 @@ import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; @@ -26,10 +30,46 @@ public enum YTestStart { gaming; /* :D */ public static void main(final String[] args) { - + System.out.println("Starting.."); + System.out.println("============================="); + int i = 100; + long firstCheck; + startWatcher(); + { + YTcpServer server = new YTcpServer(IPAddress.LOOPBACK, 2173); + server.listen(); + YTcpClient client = new YTcpClient(); + while (i > 0) { + client.send(("hello world " + YRandom.BASIC.nextInt(9999)).getBytes(StandardCharsets.UTF_8)); + i--; + kThread.sleep(50); + } + client.close(); + server.close(); + } + firstCheck = stopWatcher() - 50 * 100 /* remove the amount of time we sleep */; + + + System.out.println("Sending random bytes took " + firstCheck + "ms"); + + startWatcher(); + int massConnectClientSize = 40; + { + YTcpServer server = new YTcpServer(IPAddress.LOOPBACK, 2173); + server.listen(); + for (int j = massConnectClientSize; j > 0; j--) { + YTcpClient client = new YTcpClient(); + client.connect(IPAddress.LOOPBACK, 2173); + client.send("yystal".getBytes(StandardCharsets.UTF_8)); + kThread.sleep(50); + } + } + long secondCheck = stopWatcher() - massConnectClientSize * 50; /* remove the amount of time we sleep */; + System.out.println("Mass connect check took: (" + massConnectClientSize + " clients) " + secondCheck + "ms"); + System.out.println("============================="); kThread.sleep(1099900); }