generated from CleanroomMC/ForgeDevEnv
-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathGroovyScript.java
More file actions
324 lines (293 loc) · 13.4 KB
/
GroovyScript.java
File metadata and controls
324 lines (293 loc) · 13.4 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
package com.cleanroommc.groovyscript;
import com.cleanroommc.groovyscript.api.GroovyBlacklist;
import com.cleanroommc.groovyscript.api.GroovyLog;
import com.cleanroommc.groovyscript.command.CustomClickAction;
import com.cleanroommc.groovyscript.command.GSCommand;
import com.cleanroommc.groovyscript.compat.content.GroovyResourcePack;
import com.cleanroommc.groovyscript.compat.mods.ModSupport;
import com.cleanroommc.groovyscript.compat.mods.tinkersconstruct.TinkersConstruct;
import com.cleanroommc.groovyscript.compat.vanilla.VanillaModule;
import com.cleanroommc.groovyscript.compat.vanilla.command.infoparser.StandardInfoParserRegistry;
import com.cleanroommc.groovyscript.core.mixin.DefaultResourcePackAccessor;
import com.cleanroommc.groovyscript.documentation.Documentation;
import com.cleanroommc.groovyscript.documentation.linkgenerator.LinkGeneratorHooks;
import com.cleanroommc.groovyscript.event.EventHandler;
import com.cleanroommc.groovyscript.helper.JsonHelper;
import com.cleanroommc.groovyscript.keybind.GroovyScriptKeybinds;
import com.cleanroommc.groovyscript.mapper.ObjectMapper;
import com.cleanroommc.groovyscript.mapper.ObjectMapperManager;
import com.cleanroommc.groovyscript.network.NetworkHandler;
import com.cleanroommc.groovyscript.registry.ReloadableRegistryManager;
import com.cleanroommc.groovyscript.sandbox.*;
import com.cleanroommc.groovyscript.sandbox.mapper.GroovyDeobfMapper;
import com.cleanroommc.groovyscript.sandbox.security.GrSMetaClassCreationHandle;
import com.cleanroommc.groovyscript.server.GroovyScriptLanguageServer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import groovy.lang.GroovySystem;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.command.ICommandSender;
import net.minecraft.item.Item;
import net.minecraft.util.text.Style;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.event.FMLConstructionEvent;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.FMLLaunchHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Random;
@GroovyBlacklist
@Mod(modid = GroovyScript.ID,
name = GroovyScript.NAME,
version = GroovyScript.VERSION,
dependencies = "after:mixinbooter@[8.0,);",
guiFactory = "com.cleanroommc.groovyscript.DisabledConfigGui")
@Mod.EventBusSubscriber(modid = GroovyScript.ID)
public class GroovyScript {
public static final String ID = Tags.MODID;
public static final String NAME = "GroovyScript";
public static final String VERSION = Tags.VERSION;
public static final String MC_VERSION = "1.12.2";
public static final String GROOVY_VERSION = Tags.GROOVY_VERSION;
public static final Logger LOGGER = LogManager.getLogger(ID);
private static File minecraftHome;
private static File scriptPath;
private static File runConfigFile;
private static File resourcesFile;
private static RunConfig runConfig;
private static GroovyScriptSandbox sandbox;
private static ModContainer scriptMod;
private static Thread languageServerThread;
public static final Random RND = new Random();
@Mod.EventHandler
public void onConstruction(FMLConstructionEvent event) {
MinecraftForge.EVENT_BUS.register(this);
MinecraftForge.EVENT_BUS.register(EventHandler.class);
NetworkHandler.init();
GroovySystem.getMetaClassRegistry().setMetaClassCreationHandle(GrSMetaClassCreationHandle.INSTANCE);
GroovyDeobfMapper.init();
LinkGeneratorHooks.init();
ReloadableRegistryManager.init();
try {
sandbox = new GroovyScriptSandbox(scriptPath, FileUtil.makeFile(FileUtil.getMinecraftHome(), "cache", "groovy"));
} catch (MalformedURLException e) {
throw new IllegalStateException("Error initializing sandbox!");
}
ModSupport.INSTANCE.setup(event.getASMHarvestedData());
FluidRegistry.enableUniversalBucket();
getRunConfig().initPackmode();
}
@Mod.EventHandler
@SideOnly(Side.CLIENT)
public void onClientConstruction(FMLConstructionEvent event) {
MinecraftForge.EVENT_BUS.register(GroovyScriptKeybinds.class);
// this resource pack must be added in construction
((DefaultResourcePackAccessor) Minecraft.getMinecraft()).get().add(new GroovyResourcePack());
}
@Mod.EventHandler
public void onInit(FMLInitializationEvent event) {
if (ModSupport.TINKERS_CONSTRUCT.isLoaded()) TinkersConstruct.init();
if (Boolean.parseBoolean(System.getProperty("groovyscript.run_ls"))) {
runLanguageServer();
}
}
@Mod.EventHandler
@SideOnly(Side.CLIENT)
public void onClientInit(FMLInitializationEvent event) {
GroovyScriptKeybinds.initialize();
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onRegisterItem(RegistryEvent.Register<Item> event) {
if (ModSupport.TINKERS_CONSTRUCT.isLoaded()) TinkersConstruct.preInit();
}
@ApiStatus.Internal
public static void initializeRunConfig(File minecraftHome) {
GroovyScript.minecraftHome = minecraftHome;
// If we are launching with the environment variable set to use the examples folder, use the examples folder for easy and consistent testing.
if (Boolean.parseBoolean(System.getProperty("groovyscript.use_examples_folder"))) {
scriptPath = new File(minecraftHome.getParentFile(), "examples");
} else {
scriptPath = new File(minecraftHome, "groovy");
}
try {
scriptPath = scriptPath.getCanonicalFile();
} catch (IOException e) {
GroovyLog.get().error("Failed to canonicalize groovy script path '" + scriptPath + "'!");
GroovyLog.get().exception(e);
}
runConfigFile = new File(scriptPath, "runConfig.json");
resourcesFile = new File(scriptPath, "assets");
reloadRunConfig(true);
}
@ApiStatus.Internal
public static void initializeGroovyPreInit() {
// called via mixin in between construction and fml pre init
ObjectMapperManager.init();
StandardInfoParserRegistry.init();
VanillaModule.initializeBinding();
ModSupport.init();
for (ObjectMapper<?> goh : ObjectMapperManager.getObjectMappers()) {
getSandbox().registerBinding(goh);
}
if (FMLLaunchHandler.isDeobfuscatedEnvironment()) Documentation.generate();
runGroovyScriptsInLoader(LoadStage.PRE_INIT);
}
@ApiStatus.Internal
public static long runGroovyScriptsInLoader(LoadStage loadStage) {
// called via mixin between fml post init and load complete
if (!getRunConfig().isLoaderConfigured(loadStage.getName())) {
GroovyLog.get().infoMC("Skipping load stage {}, since no scripts are configured!", loadStage.getName());
return -1;
}
if (scriptMod == null) scriptMod = Loader.instance().getIndexedModList().get(getRunConfig().getPackId());
ModContainer current = Loader.instance().activeModContainer();
Loader.instance().setActiveModContainer(scriptMod);
long time = System.currentTimeMillis();
getSandbox().run(loadStage);
time = System.currentTimeMillis() - time;
LOGGER.info("Running Groovy scripts during {} took {} ms", loadStage.getName(), time);
Loader.instance().setActiveModContainer(current);
return time;
}
@Mod.EventHandler
public void onPostInit(FMLPostInitializationEvent event) {
CustomClickAction.registerAction("copy", value -> {
GuiScreen.setClipboardString(value);
Minecraft.getMinecraft().player.sendMessage(new TextComponentTranslation("groovyscript.command.copy.copied_start")
.appendSibling(new TextComponentString(value).setStyle(new Style().setColor(TextFormatting.GOLD)))
.appendSibling(new TextComponentTranslation("groovyscript.command.copy.copied_end")));
});
}
@Mod.EventHandler
public void onServerLoad(FMLServerStartingEvent event) {
event.registerServerCommand(new GSCommand());
}
@NotNull
public static String getScriptPath() {
return getScriptFile().getPath();
}
@NotNull
public static File getMinecraftHome() {
if (minecraftHome == null) {
throw new IllegalStateException("GroovyScript is not yet loaded!");
}
return minecraftHome;
}
@NotNull
public static File getScriptFile() {
if (scriptPath == null) {
throw new IllegalStateException("GroovyScript is not yet loaded!");
}
return scriptPath;
}
@NotNull
public static File getResourcesFile() {
if (resourcesFile == null) {
throw new IllegalStateException("GroovyScript is not yet loaded!");
}
return resourcesFile;
}
@NotNull
public static File getRunConfigFile() {
if (runConfigFile == null) {
throw new IllegalStateException("GroovyScript is not yet loaded!");
}
return runConfigFile;
}
@NotNull
public static GroovyScriptSandbox getSandbox() {
if (sandbox == null) {
throw new IllegalStateException("GroovyScript is not yet loaded!");
}
return sandbox;
}
public static boolean isSandboxLoaded() {
return sandbox != null;
}
public static RunConfig getRunConfig() {
return runConfig;
}
@ApiStatus.Internal
public static void reloadRunConfig(boolean init) {
JsonElement element = JsonHelper.loadJson(runConfigFile);
if (element == null || !element.isJsonObject()) element = new JsonObject();
JsonObject json = element.getAsJsonObject();
if (runConfig == null) {
if (!Files.exists(runConfigFile.toPath())) {
json = RunConfig.createDefaultJson();
runConfig = createRunConfig(json);
} else {
runConfig = new RunConfig(json);
}
}
runConfig.reload(json, init);
}
private static RunConfig createRunConfig(JsonObject json) {
JsonHelper.saveJson(runConfigFile, json);
File main = new File(scriptPath.getPath() + File.separator + "postInit" + File.separator + "main.groovy");
if (!Files.exists(main.toPath())) {
try {
main.getParentFile().mkdirs();
Files.write(main.toPath(), "\nprintln('Hello World!')\n".getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return new RunConfig(json);
}
public static void postScriptRunResult(ICommandSender sender, boolean onlyLogFails, boolean running, boolean packmode, long time) {
List<String> errors = GroovyLogImpl.LOG.collectErrors();
if (errors.isEmpty()) {
if (!onlyLogFails) {
if (running) {
String s = packmode ? "changes packmode" : "reloaded scripts";
sender.sendMessage(new TextComponentString(TextFormatting.GREEN + "Successfully " + s + TextFormatting.WHITE + " in " + time + "ms"));
} else {
sender.sendMessage(new TextComponentString(TextFormatting.GREEN + "No syntax errors found :)"));
}
}
} else {
String executing = running ? "running" : "checking";
sender.sendMessage(new TextComponentString(TextFormatting.RED + "Found " + errors.size() + " errors while " + executing + " scripts"));
int n = errors.size();
if (errors.size() >= 10) {
sender.sendMessage(new TextComponentString("Displaying the first 7 errors:"));
n = 7;
}
for (int i = 0; i < n; i++) {
sender.sendMessage(new TextComponentString(TextFormatting.RED + errors.get(i)));
}
GSCommand.postLogFiles(sender);
}
}
public static boolean runLanguageServer() {
if (languageServerThread != null) return false;
languageServerThread = new Thread(() -> GroovyScriptLanguageServer.listen(getSandbox().getScriptRoot()));
languageServerThread.start();
return true;
}
}