/
ConsoleReader.java
251 lines (235 loc) · 9.94 KB
/
ConsoleReader.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
package net.ME1312.Galaxi.Engine.Library;
import jline.console.completer.Completer;
import jline.console.completer.StringsCompleter;
import net.ME1312.Galaxi.Engine.GalaxiEngine;
import net.ME1312.Galaxi.Engine.PluginManager;
import net.ME1312.Galaxi.Event.ConsoleChatEvent;
import net.ME1312.Galaxi.Event.ConsoleCommandEvent;
import net.ME1312.Galaxi.Library.Callback;
import net.ME1312.Galaxi.Library.Container;
import net.ME1312.Galaxi.Library.Util;
import net.ME1312.Galaxi.Plugin.Command.Command;
import net.ME1312.Galaxi.Plugin.Command.CommandSender;
import net.ME1312.Galaxi.Plugin.Command.CompletionHandler;
import net.ME1312.Galaxi.Plugin.Command.ConsoleCommandSender;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Console Reader Class
*/
public class ConsoleReader extends Thread implements Completer {
private Container<Boolean> running;
private jline.console.ConsoleReader jline;
private Callback<String> chat = null;
private GalaxiEngine engine;
/**
* Create a ConsoleReader
*
* @param engine GalaxiEngine
* @param jline JLine Reader
* @param status Status Container
*/
public ConsoleReader(GalaxiEngine engine, jline.console.ConsoleReader jline, Container<Boolean> status) {
this.engine = engine;
this.jline = jline;
this.running = status;
jline.addCompleter(this);
}
/**
* Set a chat listener (commands not starting with <b>/</b> will become chat messages)
*
* @param listener Chat Listener
*/
public void setChatListener(Callback<String> listener) {
this.chat = listener;
}
@SuppressWarnings("unchecked")
@Override
public int complete(String full, int cursor, List<CharSequence> candidates) {
if (full != null && full.length() > 0 && (chat == null || full.startsWith("/"))) {
String before = "";
String last = null;
LinkedList<String> args = new LinkedList<String>();
Matcher parser = Pattern.compile("(?:^|\\s+)(\"(?:\\\\\"|[^\"])+\"?|(?:\\\\\\s|[^\\s])+)?").matcher(full);
while (parser.find()) {
if (last != null) before += last;
String arg = parser.group(1);
if (arg != null) {
if (arg.startsWith("\"")) arg = arg.substring(1, arg.length() - ((arg.endsWith("\"")) ? 1 : 0));
arg = parseCommand(arg);
} else arg = "";
args.add(arg);
last = parser.group();
}
String cmd = args.get(0);
args.remove(0);
if (cmd.startsWith("/")) cmd = cmd.substring(1);
TreeMap<String, Command> commands;
try {
Field f = PluginManager.class.getDeclaredField("commands");
f.setAccessible(true);
commands = (TreeMap<String, Command>) f.get(engine.getPluginManager());
f.setAccessible(false);
} catch (Exception e) {
e.printStackTrace();
commands = new TreeMap<String, Command>();
}
if (args.size() == 0) {
for (String handle : commands.keySet())
if (handle.startsWith(cmd.toLowerCase()))
candidates.add(((full.startsWith("/"))?"/":"") + handle.replace("\\", "\\\\").replace("\n", "\\n").replace("\"", "\\\"").replace(" ", "\\ "));
} else if (commands.keySet().contains(cmd.toLowerCase())) {
CompletionHandler autocompletor = commands.get(cmd.toLowerCase()).autocomplete();
if (autocompletor != null)
for (String autocomplete : autocompletor.complete(ConsoleCommandSender.get(), cmd, args.toArray(new String[args.size()])))
if (!Util.isNull(autocomplete) && autocomplete.length() > 0) candidates.add(before + ' ' + autocomplete.replace("\\", "\\\\").replace("\n", "\\n").replace("\"", "\\\"").replace(" ", "\\ "));
}
}
return candidates.isEmpty()?-1:0;
}
/**
* Start the ConsoleReader loop
*/
public void run() {
try {
String line;
while (running.get() && (line = jline.readLine(">")) != null) {
if (!running.get() || line.replaceAll("\\s", "").length() == 0) continue;
if (chat != null && !line.startsWith("/")) {
try {
ConsoleChatEvent event = new ConsoleChatEvent(engine, Util.unescapeJavaString(line));
engine.getPluginManager().executeEvent(event);
if (!event.isCancelled()) chat.run(event.getMessage());
} catch (Exception e) {
engine.getAppInfo().getLogger().error.print(e);
}
} else {
runCommand(ConsoleCommandSender.get(), line);
}
}
} catch (Exception e) {
engine.getAppInfo().getLogger().error.println(e);
}
}
/**
* Run a command
*
* @param sender Command Sender
* @param command Command
*/
@SuppressWarnings("unchecked")
public void runCommand(CommandSender sender, String command) {
if (Util.isNull(sender, command)) throw new NullPointerException();
ConsoleCommandEvent event = new ConsoleCommandEvent(engine, command);
engine.getPluginManager().executeEvent(event);
if (!event.isCancelled()) {
String line = event.getCommand();
LinkedList<String> args = new LinkedList<String>();
Matcher parser = Pattern.compile("(?:^|\\s+)(\"(?:\\\\\"|[^\"])+\"?|(?:\\\\\\s|[^\\s])+)").matcher(line);
while (parser.find()) {
String arg = parser.group(1);
if (arg.startsWith("\"")) arg = arg.substring(1, arg.length() - ((arg.endsWith("\""))?1:0));
arg = parseCommand(arg);
args.add(arg);
}
String cmd = args.get(0);
args.remove(0);
if (cmd.startsWith("/")) cmd = cmd.substring(1);
TreeMap<String, Command> commands;
try {
Field f = PluginManager.class.getDeclaredField("commands");
f.setAccessible(true);
commands = (TreeMap<String, Command>) f.get(engine.getPluginManager());
f.setAccessible(false);
} catch (Exception e) {
e.printStackTrace();
commands = new TreeMap<String, Command>();
}
if (commands.keySet().contains(cmd.toLowerCase())) {
try {
commands.get(cmd.toLowerCase()).command(sender, cmd, args.toArray(new String[args.size()]));
} catch (Exception e) {
engine.getAppInfo().getLogger().error.println(new InvocationTargetException(e, "Uncaught exception while running command"));
}
} else {
String s = cmd.replace("\\", "\\\\").replace("\n", "\\n").replace("\"", "\\\"").replace(" ", "\\ ");
for (String arg : args) {
s += ' ' + arg.replace("\\", "\\\\").replace("\n", "\\n").replace("\"", "\\\"").replace(" ", "\\ ");
}
engine.getAppInfo().getLogger().message.println("Unknown Command - " + s);
}
try {
jline.getOutput().write("\b \b");
} catch (Exception e) {
engine.getAppInfo().getLogger().error.print(e);
}
}
}
/**
* Parse escapes in a command
*
* @param str String
* @return Unescaped String
*/
private String parseCommand(String str) {
StringBuilder sb = new StringBuilder(str.length());
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == '\\') {
char nextChar = (i == str.length() - 1) ? '\\' : str
.charAt(i + 1);
// Octal escape?
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < str.length() - 1) && str.charAt(i + 1) >= '0'
&& str.charAt(i + 1) <= '7') {
code += str.charAt(i + 1);
i++;
if ((i < str.length() - 1) && str.charAt(i + 1) >= '0'
&& str.charAt(i + 1) <= '7') {
code += str.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch (nextChar) {
case '\\':
ch = '\\';
break;
case 'n':
ch = '\n';
break;
case '\"':
ch = '\"';
break;
case ' ':
ch = ' ';
break;
// Hex Unicode: u????
case 'u':
if (i >= str.length() - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt(
"" + str.charAt(i + 2) + str.charAt(i + 3)
+ str.charAt(i + 4) + str.charAt(i + 5), 16);
sb.append(Character.toChars(code));
i += 5;
continue;
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
}