/
GalaxiEngine.java
281 lines (244 loc) · 10.1 KB
/
GalaxiEngine.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
package net.ME1312.Galaxi.Engine;
import net.ME1312.Galaxi.Engine.Library.ConsoleReader;
import net.ME1312.Galaxi.Engine.Library.DefaultCommands;
import net.ME1312.Galaxi.Engine.Library.Log.SystemLogger;
import net.ME1312.Galaxi.Event.GalaxiStartEvent;
import net.ME1312.Galaxi.Event.GalaxiStopEvent;
import net.ME1312.Galaxi.Galaxi;
import net.ME1312.Galaxi.Library.Config.YAMLSection;
import net.ME1312.Galaxi.Library.Container.Container;
import net.ME1312.Galaxi.Library.Log.LogLevel;
import net.ME1312.Galaxi.Library.Log.Logger;
import net.ME1312.Galaxi.Library.Map.ObjectMap;
import net.ME1312.Galaxi.Library.Platform;
import net.ME1312.Galaxi.Library.UniversalFile;
import net.ME1312.Galaxi.Library.Util;
import net.ME1312.Galaxi.Library.Version.Version;
import net.ME1312.Galaxi.Plugin.App;
import net.ME1312.Galaxi.Plugin.Plugin;
import net.ME1312.Galaxi.Plugin.PluginInfo;
import org.json.JSONObject;
import javax.swing.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLStreamHandler;
import java.nio.charset.Charset;
import java.util.*;
import java.util.Timer;
import java.util.concurrent.TimeUnit;
import java.util.jar.Manifest;
import static net.ME1312.Galaxi.Engine.GalaxiOption.*;
/**
* Galaxi Engine Main Class
*/
@App(name = "GalaxiEngine", version = "3.4.0a", authors = "ME1312", description = "An engine for command line Java applications", website = "https://github.com/ME1312/GalaxiEngine")
public class GalaxiEngine extends Galaxi {
private final PluginManager pluginManager = new PluginManager(this);
private final UniversalFile dir = new UniversalFile(RUNTIME_DIRECTORY.app());
private final UniversalFile idir;
private final ConsoleReader console;
private final PluginInfo app;
private final PluginInfo engine;
private static GalaxiEngine instance = null;
private final Container<Boolean> running = new Container<>(false);
private Runnable onStop = null;
/**
* Initialize the Galaxi Engine
*
* @see App @App
* @see Plugin @Plugin
* @param app Main class object of the app (annotated with @App/@Plugin)
* @return The GalaxiEngine
*/
public static GalaxiEngine init(Object app) throws Exception {
if (Util.isNull(app)) throw new NullPointerException();
if (instance == null) {
return new GalaxiEngine(PluginInfo.getPluginInfo(app));
} else throw new IllegalStateException("Engine already initialized");
}
/**
* Initialize the Galaxi Engine
*
* @param app PluginInfo for the app
* @return The GalaxiEngine
*/
public static GalaxiEngine init(PluginInfo app) throws Exception {
if (Util.isNull(app)) throw new NullPointerException();
if (instance == null) {
return new GalaxiEngine(app);
} else throw new IllegalStateException("Engine already initialized");
}
/**
* Get the GalaxiEngine
*
* @return The GalaxiEngine
*/
public static GalaxiEngine getInstance() {
if (instance == null) throw new IllegalStateException("Illegal call to getInstance() before engine initialization");
return instance;
}
@SuppressWarnings("unchecked")
private GalaxiEngine(PluginInfo app) throws Exception {
System.setProperty("apple.laf.useScreenMenuBar", "true");
instance = this;
this.engine = PluginInfo.getPluginInfo(this);
this.app = (app == null)?engine:app;
if (APPDATA_DIRECTORY.app() == Platform.getSystem().getAppDataDirectory()) APPDATA_DIRECTORY.value(new File(Platform.getSystem().getAppDataDirectory(), this.getAppInfo().getName()));
Util.reflect(GalaxiOption.class.getDeclaredField("lock"), null, true);
this.idir = new UniversalFile(APPDATA_DIRECTORY.app());
Manifest manifest = new Manifest(GalaxiEngine.class.getResourceAsStream("/META-INF/GalaxiEngine.MF"));
if (manifest.getMainAttributes().getValue("Implementation-Version") != null && manifest.getMainAttributes().getValue("Implementation-Version").length() > 0)
engine.setSignature(new Version(manifest.getMainAttributes().getValue("Implementation-Version")));
engine.setIcon(GalaxiEngine.class.getResourceAsStream("/net/ME1312/Galaxi/Engine/Library/Files/GalaxiIcon.png"));
Util.isException(() -> UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()));
pluginManager.findClasses(engine.get().getClass());
pluginManager.findClasses(this.app.get().getClass());
if (!(SHOW_DEBUG_MESSAGES.usr().equalsIgnoreCase("true") || (SHOW_DEBUG_MESSAGES.usr().length() <= 0 && SHOW_DEBUG_MESSAGES.app())))
Logger.addStaticFilter((stream, message) -> (stream.getLevel() != LogLevel.DEBUG)?null:false);
this.console = new ConsoleReader(this, running);
this.app.getLogger().info.println("Loading " + engine.getName() + " v" + engine.getVersion().toString() + " Libraries");
if (app == null) this.app.getLogger().warn.println("GalaxiEngine is running in standalone mode");
else if (engine.getName().equalsIgnoreCase(this.app.getName())) throw new IllegalStateException("App name cannot be the same as the Engine's name");
DefaultCommands.load(this);
URL.setURLStreamHandlerFactory(protocol -> {
HashMap<String, URLStreamHandler> protocols;
try {
protocols = Util.reflect(Galaxi.class.getDeclaredField("protocols"), this);
} catch (Exception e) {
e.printStackTrace();
protocols = new HashMap<String, URLStreamHandler>();
}
if (protocols.keySet().contains(protocol.toLowerCase())) {
return protocols.get(protocol.toLowerCase());
} else {
return null;
}
});
if (engine == this.app || !GalaxiEngine.class.getProtectionDomain().getCodeSource().getLocation().equals(this.app.get().getClass().getProtectionDomain().getCodeSource().getLocation())) {
engine.setUpdateChecker(() -> {
try {
YAMLSection tags = new YAMLSection(new JSONObject("{\"tags\":" + Util.readAll(new BufferedReader(new InputStreamReader(new URL("https://api.github.com/repos/ME1312/GalaxiEngine/git/refs/tags").openStream(), Charset.forName("UTF-8")))) + '}'));
List<Version> versions = new LinkedList<Version>();
Version updversion = getEngineInfo().getVersion();
int updcount = 0;
for (ObjectMap<String> tag : tags.getMapList("tags")) versions.add(Version.fromString(tag.getString("ref").substring(10)));
Collections.sort(versions);
for (Version version : versions) {
if (version.compareTo(updversion) > 0) {
updversion = version;
updcount++;
}
}
if (updcount != 0) {
getAppInfo().getLogger().message.println(engine.getName() + " v" + updversion + " is available. You are " + updcount + " version" + ((updcount == 1)?"":"s") + " behind.");
return true;
}
} catch (Exception e) {}
return false;
});
}
}
/**
* Start the GalaxiEngine
*/
public void start() {
start(null);
}
/**
* Start the GalaxiEngine
*
* @param callback Callback for when Galaxi is stopped
*/
public void start(Runnable callback) {
if (!running.value()) {
try {
onStop = callback;
running.value(true);
Util.isException(() -> Util.<Thread>reflect(ConsoleReader.class.getDeclaredField("thread"), console).start());
pluginManager.executeEvent(new GalaxiStartEvent(this));
} catch (Exception e) {}
new Timer(getEngineInfo().getName() + "::Routine_Update_Check").schedule(new TimerTask() {
@Override
public void run() {
try {
if (engine.getUpdateChecker() != null) engine.getUpdateChecker().run();
if (engine != app && app.getUpdateChecker() != null) app.getUpdateChecker().run();
} catch (Exception e) {}
}
}, 0, TimeUnit.DAYS.toMillis(2));
}
}
/**
* Stop the GalaxiEngine
*/
public void stop() {
stop(0);
}
/**
* Stop the GalaxiEngine
*
* @param code Exit Code
*/
public void stop(int code) {
if (!stopping) {
stopping = true;
GalaxiStopEvent event = new GalaxiStopEvent(this, code);
pluginManager.executeEvent(event);
if (!event.isCancelled()) {
exit(code);
} else stopping = false;
}
}
/**
* Force stop the GalaxiEngine
*
* @param code Exit Code
*/
public void terminate(int code) {
stopping = true;
GalaxiStopEvent event = new GalaxiStopEvent(this, code);
pluginManager.executeEvent(event);
exit(code);
}
private boolean stopping = false;
private void exit(int code) {
if (onStop != null) try {
onStop.run();
} catch (Throwable e) {
app.getLogger().error.println(e);
}
running.value(false);
Util.isException(() -> Util.reflect(SystemLogger.class.getDeclaredMethod("stop"), null));
System.exit(code);
}
/**
* Get the ConsoleReader
*
* @return ConsoleReader
*/
public ConsoleReader getConsoleReader() {
return console;
}
@Override
public PluginManager getPluginManager() {
return pluginManager;
}
@Override
public UniversalFile getAppDataDirectory() {
return idir;
}
@Override
public UniversalFile getRuntimeDirectory() {
return dir;
}
@Override
public PluginInfo getAppInfo() {
return app;
}
@Override
public PluginInfo getEngineInfo() {
return engine;
}
}