summaryrefslogtreecommitdiff
path: root/com/nemez/cmdmgr/CommandManager.java
blob: 8743db8e5493405822bfde663db9d51660d0b0c4 (plain)
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
package com.nemez.cmdmgr;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.logging.Level;

import org.bukkit.plugin.java.JavaPlugin;

import com.nemez.cmdmgr.component.ArgumentComponent;
import com.nemez.cmdmgr.component.ByteComponent;
import com.nemez.cmdmgr.component.ChainComponent;
import com.nemez.cmdmgr.component.ConstantComponent;
import com.nemez.cmdmgr.component.DoubleComponent;
import com.nemez.cmdmgr.component.FloatComponent;
import com.nemez.cmdmgr.component.ICommandComponent;
import com.nemez.cmdmgr.component.IntegerComponent;
import com.nemez.cmdmgr.component.LongComponent;
import com.nemez.cmdmgr.component.ShortComponent;
import com.nemez.cmdmgr.component.StringComponent;
import com.nemez.cmdmgr.util.BranchStack;
import com.nemez.cmdmgr.util.Executable;
import com.nemez.cmdmgr.util.HelpPageCommand;
import com.nemez.cmdmgr.util.Property;

/**
 *  Example command.cmd
 *  
 *  command home:
 *  	set [string:name]:
 *  		run home_set name
 *  		help Set a new home
 *  		perm home.set
 *  	del [string:name]:
 *  		run home_del name
 *  		help Delete home\n&CCannot be undone!
 *  		perm home.del
 *  	list:
 *  		run home_list
 *  		help Show all homes
 *  		perm home.list
 *  	[string:name]:
 *  		run home_tp name
 *  		help Teleport to specified home
 *  		perm home.tp
 *
 *  Generated in-game command structure:
 *  (will only show commands the user has permission to execute)
 *  
 *  /home set <name>
 *  /home del <name>
 *  /home list
 *  /home <name>
 *  /home help
 *  
 *   Java code:
 *   
 *   @Command(hook="home_set")
 *   public void executeHomeSet(String name) {
 *     ...
 *   }
 *   
 *   @Command(hook="home_del")
 *   public void executeHomeDelete(String name) {
 *     ...
 *   }
 *   
 *   @Command(hook="home_list")
 *   public void executeHomeList() {
 *     ...
 *   }
 *   
 *   @Command(hook="home_tp")
 *   public void executeHomeTeleport(String name) {
 *     ...
 *   }
 */

public class CommandManager {

	public static boolean debugOutput = false;
	public static boolean errors = false;
	
	public static boolean registerCommand(String cmdSourceCode, Object commandHandler, JavaPlugin plugin) {
		if (cmdSourceCode == null || commandHandler == null || plugin == null) {
			return false;
		}
		Method[] methods = commandHandler.getClass().getMethods();
		ArrayList<Method> finalMethods = new ArrayList<Method>();
		
		for (Method m : methods) {
			if (m.getAnnotationsByType(Command.class).length > 0 && (m.getModifiers() & Modifier.STATIC) == 0) {
				finalMethods.add(m);
			}
		}
		return parse(cmdSourceCode, finalMethods, plugin, commandHandler);
	}
	
	public static boolean registerCommand(File sourceFile, Object commandHandler, JavaPlugin plugin) {
		StringBuilder src = new StringBuilder();
		String buf = "";
		try {
			BufferedReader reader = new BufferedReader(new FileReader(sourceFile));
			while ((buf = reader.readLine()) != null) {
				src.append(buf);
			}
			reader.close();
		} catch (Exception e) {
			plugin.getLogger().log(Level.WARNING, "Error while loading command file. (" + sourceFile.getAbsolutePath() + ")");
			plugin.getLogger().log(Level.WARNING, e.getCause().toString());
			errors = true;
			return false;
		}
		return registerCommand(src.toString(), commandHandler, plugin);
	}
	
	public static boolean registerCommand(InputStream sourceStream, Object commandHandler, JavaPlugin plugin) {
		StringBuilder src = new StringBuilder();
		String buf = "";
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(sourceStream));
			while ((buf = reader.readLine()) != null) {
				src.append(buf);
			}
			reader.close();
		} catch (Exception e) {
			plugin.getLogger().log(Level.WARNING, "Error while loading command file. (" + sourceStream.toString() + ")");
			plugin.getLogger().log(Level.WARNING, e.getCause().toString());
			errors = true;
			return false;
		}
		return registerCommand(src.toString(), commandHandler, plugin);
	}
	
	private static boolean parse(String source, ArrayList<Method> methods, JavaPlugin plugin, Object methodContainer) {
		char[] chars = source.toCharArray();
		StringBuilder buffer = new StringBuilder();
		String cmdName = null;
		boolean insideType = false;
		boolean gettingName = false;
		char previous = '\0';
		ChainComponent currentChain = new ChainComponent();
		BranchStack stack = new BranchStack();
		ArgumentComponent currentArgComp = null;
		Property currentProp = Property.NONE;
		int bracketCounter = 0;
		int line = 0;
		
		for (int i = 0; i < chars.length; i++) {
			char current = chars[i];
			
			if (current == '\n') {
				line++;
			}
			
			if (current == ':') {
				if (insideType) {
					if (currentArgComp != null) {
						plugin.getLogger().log(Level.WARNING, "Syntax error at line " + line + ": Already defining a type.");
						errors = true;
						return false;
					}else{
						currentArgComp = resolveComponentType(buffer.toString());
						buffer = new StringBuilder();
						if (currentArgComp == null) {
							plugin.getLogger().log(Level.WARNING, "Type error at line " + line + ": Invalid type.");
							errors = true;
							return false;
						}
					}
				}else{
					buffer.append(':');
				}
			}else if (current == ';') {
				if (previous == '\\') {
					buffer.append(';');
				}else{
					if (stack.get() == null) {
						plugin.getLogger().log(Level.WARNING, "Syntax error at line " + line + ": Not in code section.");
						errors = true;
						return false;
					}
					if (currentProp == Property.HELP) {
						stack.get().help = buffer.toString();
					}else if (currentProp == Property.EXECUTE) {
						stack.get().execute = buffer.toString();
					}else if (currentProp == Property.PERMISSION) {
						stack.get().permission = buffer.toString().trim();
					}else{
						plugin.getLogger().log(Level.WARNING, "Attribute error at line " + line + ": Invalid attribute type.");
						errors = true;
						return false;
					}
					currentProp = Property.NONE;
					buffer = new StringBuilder();
				}
			}else if (current == '{') {
				bracketCounter++;
				if (gettingName && cmdName == null) {
					cmdName = buffer.toString().trim();
				}else{
					if (currentArgComp == null) {
						if (buffer.toString().trim().length() > 0) {
							currentChain.append(new ConstantComponent(buffer.toString().trim()));
						}
					}else{
						currentChain.append(currentArgComp);
						currentArgComp = null;
					}
				}
				buffer = new StringBuilder();
				ChainComponent top = stack.get();
				if (top != null) {
					top.append(currentChain);
				}
				stack.push(currentChain);
				currentChain = new ChainComponent();
			}else if (current == '}') {
				bracketCounter--;
				ChainComponent popped = stack.pop();
				if (popped == null) {
					plugin.getLogger().log(Level.WARNING, "Syntax error at line " + line + ": Too many closing brackets.");
					errors = true;
					return false;
				}
				if (bracketCounter == 0) {
					postProcess(cmdName, popped, methods, plugin, methodContainer); // \o/
					buffer = new StringBuilder();
					cmdName = null;
					insideType = false;
					gettingName = false;
					previous = '\0';
					currentChain = new ChainComponent();
					stack = new BranchStack();
					currentArgComp = null;
					currentProp = Property.NONE;
					continue;
				}
				currentChain = new ChainComponent();
			}else if (current == ' ') {
				if (currentProp != Property.NONE) {
					buffer.append(' ');
				}else{
					if (buffer.toString().equals("command") && !gettingName && cmdName == null) {
						gettingName = true;
					}else if (buffer.toString().equals("help")) {
						currentProp = Property.HELP;
					}else if (buffer.toString().equals("run")) {
						currentProp = Property.EXECUTE;
					}else if (buffer.toString().equals("perm")) {
						currentProp = Property.PERMISSION;
					}else{
						if (gettingName && cmdName == null) {
							cmdName = buffer.toString().trim();
						}else{
							if (currentArgComp == null) {
								if (buffer.toString().trim().length() > 0) {
									currentChain.append(new ConstantComponent(buffer.toString().trim()));
								}
							}else{
								currentChain.append(currentArgComp);
								currentArgComp = null;
							}
						}
					}
					buffer = new StringBuilder();
				}
			}else if (current == '[') {
				if (currentProp != Property.NONE) {
					buffer.append('[');
				}else if (insideType) {
					plugin.getLogger().log(Level.WARNING, "Syntax error at line " + line + ": Invalid type declaration.");
					errors = true;
					return false;
				}else{
					insideType = true;
				}
			}else if (current == ']') {
				if (currentProp != Property.NONE) {
					buffer.append(']');
				}else if (insideType) {
					insideType = false;
					if (currentArgComp == null) {
						// this should never happen though, it should error out at the top when the type is ""
						plugin.getLogger().log(Level.WARNING, "Type error at line " + line + ": Type has to type?");
						errors = true;
						return false;
					}else{
						currentArgComp.argName = buffer.toString();
						buffer = new StringBuilder();
					}
				}else{
					plugin.getLogger().log(Level.WARNING, "Syntax error at line " + line + ": Not in type declaration.");
					errors = true;
					return false;
				}
			}else if (current == '&' && currentProp == Property.HELP) {
				if (previous == '\\') {
					buffer.append('&');
				}else{
					buffer.append('§');
				}
			}else if (current == 'n' && currentProp == Property.HELP) {
				if (previous == '\\') {
					buffer.append('\n');
				}else{
					buffer.append('n');
				}
			}else if (current == 't' && currentProp == Property.HELP) {
				if (previous == '\\') {
					buffer.append('\t');
				}else{
					buffer.append('t');
				}
			}else if (current == '\\' && currentProp == Property.HELP) {
				if (previous == '\\') {
					buffer.append('\\');
				}
			}else if (current != '\r' && current != '\n' && current != '\t') {
				buffer.append(current);
			}
			previous = current;
		}
		
		return true;
	}
	
	private static ArgumentComponent resolveComponentType(String type) {
		switch (type) {
		case "string":
			return new StringComponent();
		case "int":
		case "integer":
			return new IntegerComponent();
		case "short":
			return new ShortComponent();
		case "long":
			return new LongComponent();
		case "byte":
			return new ByteComponent();
		case "float":
			return new FloatComponent();
		case "double":
			return new DoubleComponent();
		}
		return null;
	}
	
	private static void postProcess(String cmdName, ChainComponent components, ArrayList<Method> methods, JavaPlugin plugin, Object methodContainer) {
		Executable cmd = new Executable(cmdName, constructHelpPages(cmdName, components));
		cmd.register(methods, plugin, methodContainer);
	}
	
	private static ArrayList<HelpPageCommand[]> constructHelpPages(String cmdName, ChainComponent root) {
		String[] rawLines = constructHelpPagesRecursive(root).split("\r");
		ArrayList<HelpPageCommand[]> pages = new ArrayList<HelpPageCommand[]>();
		ArrayList<String> lines = new ArrayList<String>();
		HelpPageCommand[] page = new HelpPageCommand[5];
		
		for (int i = 0; i < rawLines.length; i++) {
			if (rawLines[i].length() > 0 && !rawLines[i].equals("\0null\0null\0null\0")) {
				lines.add(rawLines[i]);
			}
		}
		
		boolean firstPass = true;
		int i;
		for (i = 0; i < lines.size(); i++) {
			if (i % 5 == 0 && !firstPass) {
				pages.add(page);
				page = new HelpPageCommand[5];
			}
			String[] cmd = lines.get(i).split("\0");
			page[i % 5] = new HelpPageCommand(cmd[1], "/" + cmdName + " " + cmd[0], cmd[3], cmd[2]);
			firstPass = false;
		}
		if (i % 5 == 0) {
			pages.add(page);
			page = new HelpPageCommand[5];
		}
		page[i % 5] = new HelpPageCommand(cmdName + ".help", "/" + cmdName + " help <page:i32>", "Shows help.", null);
		pages.add(page);
		
		return pages;
	}
	
	private static String constructHelpPagesRecursive(ICommandComponent component) {
		String data = "";
		
		if (component instanceof ChainComponent) {
			ChainComponent comp = (ChainComponent) component;
			ArrayList<String> leaves = new ArrayList<String>();
			String chain = "";
			data += "\r";
			for (ICommandComponent c : comp.getComponents()) {
				String temp = constructHelpPagesRecursive(c);
				if (c instanceof ChainComponent) {
					temp = temp.replaceAll("\r", "\r" + chain);
					leaves.add(temp);
				}else{
					chain += temp;
				}
			}
			data += chain + "\0" + comp.permission + "\0" + comp.execute + "\0" + comp.help + "\0";
			for (String s : leaves) {
				data += s;
			}
		}else{
			data += component.getComponentInfo() + " ";
		}
		
		return data;
	}
}