-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathCommunicationMod.java
More file actions
359 lines (321 loc) · 13.8 KB
/
CommunicationMod.java
File metadata and controls
359 lines (321 loc) · 13.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
352
353
354
355
356
357
358
359
package communicationmod;
import basemod.*;
import basemod.interfaces.PostDungeonUpdateSubscriber;
import basemod.interfaces.PostInitializeSubscriber;
import basemod.interfaces.PostUpdateSubscriber;
import basemod.interfaces.PreUpdateSubscriber;
import com.evacipated.cardcrawl.modthespire.lib.SpireConfig;
import com.evacipated.cardcrawl.modthespire.lib.SpireInitializer;
import com.google.gson.Gson;
import com.megacrit.cardcrawl.core.Settings;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.helpers.FontHelper;
import com.megacrit.cardcrawl.helpers.ImageMaster;
import communicationmod.patches.InputActionPatch;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.lang.ProcessBuilder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import static basemod.devcommands.ConsoleCommand.addCommand;
@SpireInitializer
public class CommunicationMod implements PostInitializeSubscriber, PostUpdateSubscriber, PostDungeonUpdateSubscriber, PreUpdateSubscriber, OnStateChangeSubscriber {
private static Process listener;
private static StringBuilder inputBuffer = new StringBuilder();
public static boolean messageReceived = false;
private static final Logger logger = LogManager.getLogger(CommunicationMod.class.getName());
private static Thread writeThread;
private static BlockingQueue<String> writeQueue;
private static Thread readThread;
private static BlockingQueue<String> readQueue;
public static boolean paused;
private static final String MODNAME = "Communication Mod";
private static final String AUTHOR = "Forgotten Arbiter";
private static final String DESCRIPTION = "This mod communicates with an external program to play Slay the Spire.";
public static boolean mustSendGameState = false;
private static ArrayList<OnStateChangeSubscriber> onStateChangeSubscribers;
private static SpireConfig communicationConfig;
private static final String COMMAND_OPTION = "command";
private static final String GAME_START_OPTION = "runAtGameStart";
private static final String VERBOSE_OPTION = "verbose";
private static final String INITIALIZATION_TIMEOUT_OPTION = "maxInitializationTimeout";
private static final String DEFAULT_COMMAND = "";
private static final long DEFAULT_TIMEOUT = 10L;
private static final boolean DEFAULT_VERBOSITY = true;
public CommunicationMod(){
BaseMod.subscribe(this);
onStateChangeSubscribers = new ArrayList<>();
CommunicationMod.subscribe(this);
readQueue = new LinkedBlockingQueue<>();
try {
Properties defaults = new Properties();
defaults.put(GAME_START_OPTION, Boolean.toString(false));
defaults.put(INITIALIZATION_TIMEOUT_OPTION, Long.toString(DEFAULT_TIMEOUT));
defaults.put(VERBOSE_OPTION, Boolean.toString(DEFAULT_VERBOSITY));
communicationConfig = new SpireConfig("CommunicationMod", "config", defaults);
String command = communicationConfig.getString(COMMAND_OPTION);
// I want this to always be saved to the file so people can set it more easily.
if (command == null) {
communicationConfig.setString(COMMAND_OPTION, DEFAULT_COMMAND);
communicationConfig.save();
}
communicationConfig.save();
} catch (IOException e) {
e.printStackTrace();
}
if(getRunOnGameStartOption()) {
boolean success = startExternalProcess();
}
}
public static void initialize() {
CommunicationMod mod = new CommunicationMod();
addCommand("comms", CommsCommand.class);
}
public void receivePreUpdate() {
if(listener != null && !listener.isAlive() && writeThread != null && writeThread.isAlive()) {
logger.info("Child process has died...");
writeThread.interrupt();
readThread.interrupt();
}
if(messageAvailable() && !paused) {
try {
boolean stateChanged = CommandExecutor.executeCommand(readMessage());
if(stateChanged) {
GameStateListener.registerCommandExecution();
}
} catch (InvalidCommandException e) {
HashMap<String, Object> jsonError = new HashMap<>();
jsonError.put("error", e.getMessage());
jsonError.put("ready_for_command", GameStateListener.isWaitingForCommand());
Gson gson = new Gson();
sendMessage(gson.toJson(jsonError));
}
}
}
public static void subscribe(OnStateChangeSubscriber sub) {
onStateChangeSubscribers.add(sub);
}
public static void publishOnGameStateChange() {
for(OnStateChangeSubscriber sub : onStateChangeSubscribers) {
sub.receiveOnStateChange();
}
}
public void receiveOnStateChange() {
sendGameState();
}
public static void queueCommand(String command) {
readQueue.add(command);
}
public void receivePostInitialize() {
setUpOptionsMenu();
}
public void receivePostUpdate() {
if(!mustSendGameState && GameStateListener.checkForMenuStateChange()) {
mustSendGameState = true;
}
if(mustSendGameState) {
publishOnGameStateChange();
mustSendGameState = false;
}
InputActionPatch.doKeypress = false;
}
public void receivePostDungeonUpdate() {
if (GameStateListener.checkForDungeonStateChange()) {
mustSendGameState = true;
}
if(AbstractDungeon.getCurrRoom().isBattleOver) {
GameStateListener.signalTurnEnd();
}
}
private void setUpOptionsMenu() {
ModPanel settingsPanel = new ModPanel();
ModLabeledToggleButton gameStartOptionButton = new ModLabeledToggleButton(
"Start external process at game launch",
350, 550, Settings.CREAM_COLOR, FontHelper.charDescFont,
getRunOnGameStartOption(), settingsPanel, modLabel -> {},
modToggleButton -> {
if (communicationConfig != null) {
communicationConfig.setBool(GAME_START_OPTION, modToggleButton.enabled);
try {
communicationConfig.save();
} catch (IOException e) {
e.printStackTrace();
}
}
});
settingsPanel.addUIElement(gameStartOptionButton);
ModLabel externalCommandLabel = new ModLabel(
"", 350, 600, Settings.CREAM_COLOR, FontHelper.charDescFont,
settingsPanel, modLabel -> {
modLabel.text = String.format("External Process Command: %s", getSubprocessCommandString());
});
settingsPanel.addUIElement(externalCommandLabel);
ModButton startProcessButton = new ModButton(
350, 650, settingsPanel, modButton -> {
BaseMod.modSettingsUp = false;
startExternalProcess();
});
settingsPanel.addUIElement(startProcessButton);
ModLabel startProcessLabel = new ModLabel(
"(Re)start external process",
475, 700, Settings.CREAM_COLOR, FontHelper.charDescFont,
settingsPanel, modLabel -> {
if(listener != null && listener.isAlive()) {
modLabel.text = "Restart external process";
} else {
modLabel.text = "Start external process";
}
});
settingsPanel.addUIElement(startProcessLabel);
ModButton editProcessButton = new ModButton(
850, 650, settingsPanel, modButton -> {});
settingsPanel.addUIElement(editProcessButton);
ModLabel editProcessLabel = new ModLabel(
"Set command (not implemented)",
975, 700, Settings.CREAM_COLOR, FontHelper.charDescFont,
settingsPanel, modLabel -> {});
settingsPanel.addUIElement(editProcessLabel);
ModLabeledToggleButton verbosityOption = new ModLabeledToggleButton(
"Suppress verbose log output",
350, 500, Settings.CREAM_COLOR, FontHelper.charDescFont,
getVerbosityOption(), settingsPanel, modLabel -> {},
modToggleButton -> {
if (communicationConfig != null) {
communicationConfig.setBool(VERBOSE_OPTION, modToggleButton.enabled);
try {
communicationConfig.save();
} catch (IOException e) {
e.printStackTrace();
}
}
});
settingsPanel.addUIElement(verbosityOption);
BaseMod.registerModBadge(ImageMaster.loadImage("Icon.png"),"Communication Mod", "Forgotten Arbiter", null, settingsPanel);
}
private void startCommunicationThreads() {
writeQueue = new LinkedBlockingQueue<>();
writeThread = new Thread(new DataWriter(writeQueue, listener.getOutputStream(), getVerbosityOption()));
writeThread.start();
readThread = new Thread(new DataReader(readQueue, listener.getInputStream(), getVerbosityOption()));
readThread.start();
}
private static void sendGameState() {
String state = GameStateConverter.getCommunicationState();
sendMessage(state);
}
public static void dispose() {
logger.info("Shutting down child process...");
if(listener != null) {
listener.destroy();
}
}
private static void sendMessage(String message) {
if(writeQueue != null && writeThread.isAlive()) {
writeQueue.add(message);
}
}
private static boolean messageAvailable() {
return readQueue != null && !readQueue.isEmpty();
}
private static String readMessage() {
if(messageAvailable()) {
return readQueue.remove();
} else {
return null;
}
}
private static String readMessageBlocking() {
try {
return readQueue.poll(getInitializationTimeoutOption(), TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to read message from subprocess.");
}
}
private static String[] getSubprocessCommand() {
if (communicationConfig == null) {
return new String[0];
}
return communicationConfig.getString(COMMAND_OPTION).trim().split("\\s+");
}
private static String getSubprocessCommandString() {
if (communicationConfig == null) {
return "";
}
return communicationConfig.getString(COMMAND_OPTION).trim();
}
private static boolean getRunOnGameStartOption() {
if (communicationConfig == null) {
return false;
}
return communicationConfig.getBool(GAME_START_OPTION);
}
private static long getInitializationTimeoutOption() {
if (communicationConfig == null) {
return DEFAULT_TIMEOUT;
}
return (long)communicationConfig.getInt(INITIALIZATION_TIMEOUT_OPTION);
}
private static boolean getVerbosityOption() {
if (communicationConfig == null) {
return DEFAULT_VERBOSITY;
}
return communicationConfig.getBool(VERBOSE_OPTION);
}
private boolean startExternalProcess() {
if(readThread != null) {
readThread.interrupt();
}
if(writeThread != null) {
writeThread.interrupt();
}
if(listener != null) {
listener.destroy();
try {
boolean success = listener.waitFor(2, TimeUnit.SECONDS);
if (!success) {
listener.destroyForcibly();
}
} catch (InterruptedException e) {
e.printStackTrace();
listener.destroyForcibly();
}
}
ProcessBuilder builder = new ProcessBuilder(getSubprocessCommand());
File errorLog = new File("communication_mod_errors.log");
builder.redirectError(ProcessBuilder.Redirect.appendTo(errorLog));
try {
listener = builder.start();
} catch (IOException e) {
logger.error("Could not start external process.");
e.printStackTrace();
}
if(listener != null) {
startCommunicationThreads();
// We wait for the child process to signal it is ready before we proceed. Note that the game
// will hang while this is occurring, and it will time out after a specified waiting time.
String message = readMessageBlocking();
if(message == null) {
// The child process waited too long to respond, so we kill it.
readThread.interrupt();
writeThread.interrupt();
listener.destroy();
logger.error("Timed out while waiting for signal from external process.");
logger.error("Check communication_mod_errors.log for stderr from the process.");
return false;
} else {
logger.info(String.format("Received message from external process: %s", message));
if (GameStateListener.isWaitingForCommand()) {
mustSendGameState = true;
}
return true;
}
}
return false;
}
}