-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathScriptContainer.java
More file actions
352 lines (306 loc) · 11.8 KB
/
Copy pathScriptContainer.java
File metadata and controls
352 lines (306 loc) · 11.8 KB
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
package noppes.npcs.controllers;
import cpw.mods.fml.common.eventhandler.Event;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.CustomNpcs;
import noppes.npcs.NBTTags;
import noppes.npcs.config.ConfigScript;
import noppes.npcs.constants.EnumScriptType;
import noppes.npcs.controllers.data.IScriptHandler;
import noppes.npcs.controllers.data.IScriptUnit;
import noppes.npcs.scripted.NpcAPI;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
public class ScriptContainer implements IScriptUnit {
private static final Object lock = new Object();
public static ScriptContainer Current;
private static String CurrentType;
public String fullscript = "";
public String script = "";
public TreeMap<Long, String> console = new TreeMap<>();
public boolean errored = false;
public List<String> scripts = new ArrayList<>();
private HashSet<String> unknownFunctions = new HashSet<>();
public long lastCreated = 0L;
private String currentScriptLanguage = null;
public ScriptEngine engine = null;
private IScriptHandler handler = null;
private boolean evaluated = false;
private static Method luaCoerce;
private static Method luaCall;
private CompiledScript compScript = null;
private final HashMap<String, ScriptObjectMirror> cachedFunctions = new HashMap<>();
public ScriptContainer(IScriptHandler handler) {
this.handler = handler;
}
public void readFromNBT(NBTTagCompound compound) {
String prevScript = this.script;
this.script = compound.getString("Script");
for (int i = 0; i < ConfigScript.ExpandedScriptLimit; i++) {
if (compound.hasKey("ExpandedScript" + i)) {
this.script += compound.getString("ExpandedScript" + i);
} else {
break;
}
}
if (!this.script.equals(prevScript)) {
this.evaluated = false;
}
this.console = NBTTags.GetLongStringMap(compound.getTagList("Console", 10));
this.scripts = NBTTags.getStringList(compound.getTagList("ScriptList", 10));
this.lastCreated = 0L;
}
public NBTTagCompound writeToNBT(NBTTagCompound compound) {
compound.setString(IScriptUnit.NBT_TYPE_KEY, IScriptUnit.TYPE_ECMASCRIPT);
if (this.script.length() < 65535) {
compound.setString("Script", this.script);
} else {
if (ConfigScript.ExpandedScriptLimit > 0) {
int i = 0;
int length = this.script.length();
while (length > 0 && i <= ConfigScript.ExpandedScriptLimit) {
String str = "";
if (i == 0) {
compound.setString("Script", this.script.substring(0, 65535));
str = this.script.substring(0, 65535);
} else {
int end = (length - 65535) >= 0 ? 65535 * (i + 1) : 65535 * i + length;
str = this.script.substring(65535 * i, end);
compound.setString("ExpandedScript" + (i - 1), str);
}
i++;
length -= str.length();
}
} else {
compound.setString("Script", this.script.substring(0, 65535));
}
}
//compound.setString("Type", this.type);
compound.setTag("Console", NBTTags.NBTLongStringMap(this.console));
compound.setTag("ScriptList", NBTTags.nbtStringList(this.scripts));
return compound;
}
private String getFullCode() {
if (!this.evaluated) {
// build includes first depending on config setting
StringBuilder sb = new StringBuilder();
if (CustomNpcs.proxy.isRunLoadedScriptsFirst()) {
this.appendExternalScripts(sb);
}
// then your per‐hook main script
if (this.script != null && !this.script.isEmpty()) {
sb.append(this.script).append("\n");
}
// build includes last if not built first
if (!CustomNpcs.proxy.isRunLoadedScriptsFirst()) {
this.appendExternalScripts(sb);
}
this.fullscript = sb.toString();
this.unknownFunctions = new HashSet<>();
}
return this.fullscript;
}
private void appendExternalScripts(StringBuilder sb) {
for (String loc : this.scripts) {
String code = ScriptController.Instance.scripts.get(loc);
if (code != null && !code.isEmpty()) {
sb.append(code).append("\n");
}
}
}
public void run(ScriptEngine engine) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
this.engine.getContext().setWriter(pw);
this.engine.getContext().setErrorWriter(pw);
try {
if (compScript == null && engine instanceof Compilable)
compScript = ((Compilable) engine).compile(getFullCode());
if (compScript != null) {
compScript.eval(engine.getContext());
} else {
engine.eval(getFullCode());
}
} catch (Throwable var14) {
this.errored = true;
var14.printStackTrace(pw);
} finally {
String errorString = sw.getBuffer().toString().trim();
this.appendConsole(errorString);
pw.close();
}
}
public void run(EnumScriptType type, Event event) {
if (!CustomNpcs.proxy.isScriptingEnabled())
return;
this.run((String) type.function, (Object) event);
}
public void run(String type, Object event) {
if (!CustomNpcs.proxy.isScriptingEnabled() || errored || !hasCode() || unknownFunctions.contains(type))
return;
this.setEngine(handler.getLanguage());
if (engine == null)
return;
if (ScriptController.Instance.lastLoaded > this.lastCreated) {
this.lastCreated = ScriptController.Instance.lastLoaded;
evaluated = false;
}
synchronized (lock) {
Current = this;
CurrentType = type;
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
engine.getContext().setWriter(pw);
engine.getContext().setErrorWriter(pw);
engine.put("API", NpcAPI.Instance());
HashMap<String, Object> engineEntries = new HashMap<>(NpcAPI.engineObjects);
for (Map.Entry<String, Object> objectEntry : engineEntries.entrySet()) {
engine.put(objectEntry.getKey(), objectEntry.getValue());
}
try {
if (!evaluated) {
this.cachedFunctions.clear();
engine.eval(getFullCode());
evaluated = true;
}
if (engine.getFactory().getLanguageName().equals("lua")) {
Object ob = engine.get(type);
if (ob != null) {
if (luaCoerce == null) {
luaCoerce = Class.forName("org.luaj.vm2.lib.jse.CoerceJavaToLua").getMethod("coerce", Object.class);
luaCall = ob.getClass().getMethod("call", Class.forName("org.luaj.vm2.LuaValue"));
}
luaCall.invoke(ob, luaCoerce.invoke(null, event));
} else {
unknownFunctions.add(type);
}
} else {
if (!this.cachedFunctions.containsKey(type)) {
ScriptObjectMirror global = (ScriptObjectMirror) engine.getBindings(ScriptContext.ENGINE_SCOPE);
ScriptObjectMirror func = (ScriptObjectMirror) global.get(type);
this.cachedFunctions.put(type, func);
}
ScriptObjectMirror func = this.cachedFunctions.get(type);
if (func != null) {
func.call(null, event);
}
}
} catch (NoSuchMethodException e) {
unknownFunctions.add(type);
} catch (Throwable e) {
errored = true;
e.printStackTrace(pw);
} finally {
appendConsole(sw.getBuffer().toString().trim());
pw.close();
Current = null;
}
}
}
public void appendConsole(String message) {
if (message != null && !message.isEmpty()) {
long time = System.currentTimeMillis();
if (this.console.containsKey(time)) {
message = (String) this.console.get(time) + "\n" + message;
}
this.console.put(time, message);
while (this.console.size() > 40) {
this.console.remove(this.console.firstKey());
}
}
}
public boolean isValid() {
return evaluated && !errored;
}
@Override
public boolean hasCode() {
if (!scripts.isEmpty())
return true;
return !this.getFullCode().isEmpty();
}
public void setEngine(String scriptLanguage) {
if (!Objects.equals(scriptLanguage, this.currentScriptLanguage)) {
this.currentScriptLanguage = scriptLanguage;
if (ConfigScript.ScriptingECMA6 && scriptLanguage.equals("ECMAScript")) {
System.setProperty("nashorn.args", "--language=es6");
}
this.engine = ScriptController.Instance.getEngineByName(scriptLanguage.toLowerCase());
this.evaluated = false;
}
}
// ==================== IScriptUnit IMPLEMENTATION ====================
@Override
public String getScript() {
return this.script;
}
@Override
public void setScript(String script) {
this.script = script;
this.evaluated = false;
}
@Override
public List<String> getExternalScripts() {
return this.scripts;
}
@Override
public void setExternalScripts(List<String> scripts) {
this.scripts = scripts;
this.evaluated = false;
}
@Override
public TreeMap<Long, String> getConsole() {
return this.console;
}
@Override
public void clearConsole() {
this.console.clear();
}
@Override
public String getLanguage() {
// If a specific language is set for this container, use it
// Otherwise fall back to the handler's language
if (currentScriptLanguage != null) {
return currentScriptLanguage;
}
return handler != null ? handler.getLanguage() : "ECMAScript";
}
@Override
public void setLanguage(String language) {
if (!Objects.equals(this.currentScriptLanguage, language)) {
this.currentScriptLanguage = language;
this.evaluated = false;
}
}
@Override
public String generateHookStub(String hookName, Object hookData) {
// ECMAScript function template
return "function " + hookName + "(event) {\n \n}\n";
}
@Override
public void ensureCompiled() {
}
@Override
public boolean hasErrored() {
return this.errored;
}
@Override
public void setErrored(boolean errored) {
this.errored = errored;
}
@Override
public boolean isJanino() {
return false;
}
}