aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/cc/polyfrost/oneconfig/utils/commands/CommandManager.java
blob: e0f47794723cddfdf97493a58d2bf4269ae6feb8 (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
420
421
422
423
424
425
426
427
428
429
430
431
432
package cc.polyfrost.oneconfig.utils.commands;

import cc.polyfrost.oneconfig.utils.commands.annotations.Command;
import cc.polyfrost.oneconfig.utils.commands.annotations.Greedy;
import cc.polyfrost.oneconfig.utils.commands.annotations.Main;
import cc.polyfrost.oneconfig.utils.commands.annotations.SubCommand;
import cc.polyfrost.oneconfig.utils.commands.arguments.*;
import cc.polyfrost.oneconfig.libs.universal.ChatColor;
import cc.polyfrost.oneconfig.libs.universal.UChat;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.BlockPos;
import net.minecraftforge.client.ClientCommandHandler;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.util.*;

/**
 * Handles the registration of OneConfig commands.
 *
 * @see Command
 */
public class CommandManager {
    public static final CommandManager INSTANCE = new CommandManager();
    private static final String NOT_FOUND_TEXT = "Command not found! Type /@ROOT_COMMAND@ help for help.";
    private static final String TOO_MANY_PARAMETERS = "There were too many / little parameters for this command! Type /@ROOT_COMMAND@ help for help.";
    private static final String METHOD_RUN_ERROR = "Error while running @ROOT_COMMAND@ method! Please report this to the developer.";
    private final HashMap<Class<?>, ArgumentParser<?>> parsers = new HashMap<>();

    private CommandManager() {
        addParser(new StringParser());
        addParser(new IntegerParser());
        addParser(new IntegerParser(), Integer.TYPE);
        addParser(new DoubleParser());
        addParser(new DoubleParser(), Double.TYPE);
        addParser(new FloatParser());
        addParser(new FloatParser(), Float.TYPE);
        addParser(new BooleanParser());
        addParser(new BooleanParser(), Boolean.TYPE);
    }

    /**
     * Adds a parser to the parsers map.
     *
     * @param parser The parser to add.
     * @param clazz  The class of the parser.
     */
    public void addParser(ArgumentParser<?> parser, Class<?> clazz) {
        parsers.put(clazz, parser);
    }

    /**
     * Adds a parser to the parsers map.
     *
     * @param parser The parser to add.
     */
    public void addParser(ArgumentParser<?> parser) {
        addParser(parser, parser.typeClass);
    }

    /**
     * Registers the provided command.
     *
     * @param clazz The command to register as a class.
     */
    public void registerCommand(Class<?> clazz) {
        if (clazz.isAnnotationPresent(Command.class)) {
            final Command annotation = clazz.getAnnotation(Command.class);

            final InternalCommand root = new InternalCommand(annotation.value(), annotation.aliases(), annotation.description().trim().isEmpty() ? "Main command for " + annotation.value() : annotation.description(), null);
            for (Method method : clazz.getDeclaredMethods()) {
                if (method.isAnnotationPresent(Main.class) && method.getParameterCount() == 0) {
                    root.invokers.add(new InternalCommand.InternalCommandInvoker(annotation.value(), annotation.aliases(), method, root));
                    break;
                }
            }
            addToInvokers(clazz.getDeclaredClasses(), root);
            ClientCommandHandler.instance.registerCommand(new CommandBase() {
                @Override
                public String getCommandName() {
                    return annotation.value();
                }

                @Override
                public String getCommandUsage(ICommandSender sender) {
                    return "/" + annotation.value();
                }

                @Override
                public void processCommand(ICommandSender sender, String[] args) {
                    handleCommand(root, annotation, args);
                }

                @Override
                public int getRequiredPermissionLevel() {
                    return -1;
                }

                @Override
                public List<String> addTabCompletionOptions(ICommandSender sender, String[] args, BlockPos pos) {
                    return handleTabCompletion(root, args);
                }
            });
        }
    }

    private void handleCommand(InternalCommand root, Command annotation, String[] args) {
        if (args.length == 0) {
            if (!root.invokers.isEmpty()) {
                try {
                    root.invokers.get(0).method.invoke(null);
                } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException |
                        ExceptionInInitializerError e) {
                    e.printStackTrace();
                    UChat.chat(ChatColor.RED.toString() + ChatColor.BOLD + METHOD_RUN_ERROR);
                }
            }
        } else {
            if (annotation.helpCommand() && args[0].equalsIgnoreCase("help")) {
                //UChat.chat(sendHelpCommand(root));
            } else {
                List<InternalCommand.InternalCommandInvoker> commands = new ArrayList<>();
                int depth = 0;
                for (InternalCommand command : root.children) {
                    int newDepth = loopThroughCommands(commands, 0, command, args);
                    if (newDepth != -1) {
                        depth = newDepth;
                        break;
                    }
                }
                if (commands.isEmpty()) {
                    if (depth == -2) {
                        UChat.chat(ChatColor.RED.toString() + ChatColor.BOLD + TOO_MANY_PARAMETERS.replace("@ROOT_COMMAND@", annotation.value()));
                    } else {
                        UChat.chat(ChatColor.RED.toString() + ChatColor.BOLD + NOT_FOUND_TEXT.replace("@ROOT_COMMAND@", annotation.value()));
                    }
                } else {
                    List<CustomError> errors = new ArrayList<>();
                    for (InternalCommand.InternalCommandInvoker invoker : commands) {
                        try {
                            List<Object> params = getParametersForInvoker(invoker, depth, args);
                            if (params.size() == 1) {
                                Object first = params.get(0);
                                if (first instanceof CustomError) {
                                    errors.add((CustomError) first);
                                    continue;
                                }
                            }
                            invoker.method.invoke(null, params.toArray());
                            return;
                        } catch (Exception e) {
                            e.printStackTrace();
                            UChat.chat(ChatColor.RED.toString() + ChatColor.BOLD + METHOD_RUN_ERROR);
                            return;
                        }
                    }
                    //noinspection ConstantConditions
                    if (!errors.isEmpty()) {
                        UChat.chat(ChatColor.RED.toString() + ChatColor.BOLD + "Multiple errors occurred:");
                        for (CustomError error : errors) {
                            UChat.chat("    " + ChatColor.RED + ChatColor.BOLD + error.message);
                        }
                    }
                }
            }
        }
    }

    private List<String> handleTabCompletion(InternalCommand root, String[] args) {
        try {
            Set<Pair<InternalCommand.InternalCommandInvoker, Integer>> commands = new HashSet<>();
            for (InternalCommand command : root.children) {
                loopThroughCommandsTab(commands, 0, command, args);
            }
            if (!commands.isEmpty()) {
                List<Triple<InternalCommand.InternalCommandInvoker, Integer, Integer>> validCommands = new ArrayList<>(); // command, depth, and all processed params
                for (Pair<InternalCommand.InternalCommandInvoker, Integer> pair : commands) {
                    InternalCommand.InternalCommandInvoker invoker = pair.getLeft();
                    int depth = pair.getRight();
                    int currentParam = 0;
                    boolean failed = false;
                    while (args.length - depth > 1) {
                        Parameter param = invoker.method.getParameters()[currentParam];
                        if (param.isAnnotationPresent(Greedy.class) && currentParam + 1 != invoker.parameterTypes.length) {
                            failed = true;
                            break;
                        }
                        ArgumentParser<?> parser = parsers.get(param.getType());
                        if (parser == null) {
                            failed = true;
                            break;
                        }
                        try {
                            Arguments arguments = new Arguments(Arrays.copyOfRange(args, depth, args.length), param.isAnnotationPresent(Greedy.class));
                            if (parser.parse(arguments) != null) {
                                depth += arguments.getPosition();
                                currentParam++;
                            } else {
                                failed = true;
                                break;
                            }
                        } catch (Exception e) {
                            failed = true;
                            break;
                        }
                    }
                    if (!failed) {
                        validCommands.add(new ImmutableTriple<>(pair.getLeft(), depth, currentParam));
                    }
                }
                if (!validCommands.isEmpty()) {
                    Set<String> completions = new HashSet<>();
                    for (Triple<InternalCommand.InternalCommandInvoker, Integer, Integer> valid : validCommands) {
                        if (valid.getMiddle() == args.length) {
                            completions.add(valid.getLeft().name);
                            completions.addAll(Arrays.asList(valid.getLeft().aliases));
                            continue;
                        }
                        if (valid.getRight() + 1 > valid.getLeft().parameterTypes.length) continue;
                        Parameter param = valid.getLeft().method.getParameters()[valid.getRight()];
                        if (param.isAnnotationPresent(Greedy.class) && valid.getRight() + 1 != valid.getLeft().parameterTypes.length) {
                            continue;
                        }
                        ArgumentParser<?> parser = parsers.get(param.getType());
                        if (parser == null) {
                            continue;
                        }
                        try {
                            Arguments arguments = new Arguments(Arrays.copyOfRange(args, valid.getMiddle(), args.length), param.isAnnotationPresent(Greedy.class));
                            List<String> possibleCompletions = parser.complete(arguments, param);
                            if (possibleCompletions != null) {
                                completions.addAll(possibleCompletions);
                            }
                        } catch (Exception ignored) {

                        }
                    }
                    return new ArrayList<>(completions);
                }
            }
        } catch (Exception ignored) {

        }
        return null;
    }

    private List<Object> getParametersForInvoker(InternalCommand.InternalCommandInvoker invoker, int depth, String[] args) {
        List<Object> parameters = new ArrayList<>();
        int processed = depth;
        int currentParam = 0;
        while (processed < args.length) {
            Parameter param = invoker.method.getParameters()[currentParam];
            if (param.isAnnotationPresent(Greedy.class) && currentParam + 1 != invoker.parameterTypes.length) {
                return Collections.singletonList(new CustomError("Parsing failed: Greedy parameter must be the last one."));
            }
            ArgumentParser<?> parser = parsers.get(param.getType());
            if (parser == null) {
                return Collections.singletonList(new CustomError("No parser for " + invoker.method.getParameterTypes()[currentParam].getSimpleName() + "! Please report this to the mod author."));
            }
            try {
                Arguments arguments = new Arguments(Arrays.copyOfRange(args, processed, args.length), param.isAnnotationPresent(Greedy.class));
                try {
                    Object a = parser.parse(arguments);
                    if (a != null) {
                        parameters.add(a);
                        processed += arguments.getPosition();
                        currentParam++;
                    } else {
                        return Collections.singletonList(new CustomError("Failed to parse " + param.getType().getSimpleName() + "! Please report this to the mod author."));
                    }
                } catch (Exception e) {
                    return Collections.singletonList(new CustomError("A " + e.getClass().getSimpleName() + " has occured while try to parse " + param.getType().getSimpleName() + "! Please report this to the mod author."));
                }
            } catch (Exception e) {
                return Collections.singletonList(new CustomError("A " + e.getClass().getSimpleName() + " has occured while try to parse " + param.getType().getSimpleName() + "! Please report this to the mod author."));
            }
        }
        return parameters;
    }

    private int loopThroughCommands(List<InternalCommand.InternalCommandInvoker> commands, int depth, InternalCommand command, String[] args) {
        int nextDepth = depth + 1;
        boolean thatOneSpecialError = false;
        if (command.isValid(args[depth], false)) {
            for (InternalCommand child : command.children) {
                if (args.length > nextDepth && child.isValid(args[nextDepth], false)) {
                    int result = loopThroughCommands(commands, nextDepth, child, args);
                    if (result > -1) {
                        return result;
                    } else if (result == -2) {
                        thatOneSpecialError = true;
                    }
                }
            }
            boolean added = false;
            for (InternalCommand.InternalCommandInvoker invoker : command.invokers) {
                if (args.length - nextDepth == invoker.parameterTypes.length) {
                    commands.add(invoker);
                    added = true;
                } else {
                    thatOneSpecialError = true;
                }
            }
            if (added) {
                return nextDepth;
            }
        }
        return thatOneSpecialError ? -2 : -1;
    }

    private void loopThroughCommandsTab(Set<Pair<InternalCommand.InternalCommandInvoker, Integer>> commands, int depth, InternalCommand command, String[] args) {
        int nextDepth = depth + 1;
        if (command.isValid(args[depth], args.length == nextDepth)) {
            if (args.length != nextDepth) {
                for (InternalCommand child : command.children) {
                    if (child.isValid(args[nextDepth], args.length == nextDepth + 1)) {
                        loopThroughCommandsTab(commands, nextDepth, child, args);
                    }
                }
            }
            for (InternalCommand.InternalCommandInvoker invoker : command.invokers) {
                commands.add(new ImmutablePair<>(invoker, nextDepth));
            }
        }
    }

    private void addToInvokers(Class<?>[] classes, InternalCommand parent) {
        for (Class<?> clazz : classes) {
            if (clazz.isAnnotationPresent(SubCommand.class)) {
                SubCommand annotation = clazz.getAnnotation(SubCommand.class);
                InternalCommand command = new InternalCommand(annotation.value(), annotation.aliases(), annotation.description(), parent);
                for (Method method : clazz.getDeclaredMethods()) {
                    if (method.isAnnotationPresent(Main.class)) {
                        command.invokers.add(new InternalCommand.InternalCommandInvoker(annotation.value(), annotation.aliases(), method, command));
                    }
                }
                parent.children.add(command);
                addToInvokers(clazz.getDeclaredClasses(), command);
            }
        }
    }

    private static class CustomError {
        public String message;

        public CustomError(String message) {
            this.message = message;
        }
    }

    private static class InternalCommand {
        public final String name;
        public final String[] aliases;
        public final String description;
        public final ArrayList<InternalCommandInvoker> invokers = new ArrayList<>();
        public final InternalCommand parent;
        public final ArrayList<InternalCommand> children = new ArrayList<>();

        public InternalCommand(String name, String[] aliases, String description, InternalCommand parent) {
            this.name = name;
            this.aliases = aliases;
            this.description = description;
            this.parent = parent;
        }

        public boolean isValid(String name, boolean tabCompletion) {
            String lowerCaseName = this.name.toLowerCase(Locale.ENGLISH);
            String lowerCaseOtherName = name.toLowerCase(Locale.ENGLISH);
            if (!tabCompletion ? lowerCaseName.equals(lowerCaseOtherName) : lowerCaseName.startsWith(lowerCaseOtherName)) {
                return true;
            } else {
                for (String alias : aliases) {
                    String lowerCaseAlias = alias.toLowerCase(Locale.ENGLISH);
                    if (!tabCompletion ? lowerCaseAlias.equals(lowerCaseOtherName) : lowerCaseAlias.startsWith(lowerCaseOtherName)) {
                        return true;
                    }
                }
            }
            return false;
        }

        @Override
        public String toString() {
            return "InternalCommand{" +
                    "name='" + name + '\'' +
                    ", aliases=" + Arrays.toString(aliases) +
                    ", description='" + description + '\'' +
                    ", invokers=" + invokers +
                    '}';
        }

        public static class InternalCommandInvoker {
            public final String name;
            public final String[] aliases;
            public final Method method;
            public final Parameter[] parameterTypes;
            public final InternalCommand parent;

            public InternalCommandInvoker(String name, String[] aliases, Method method, InternalCommand parent) {
                if (!Modifier.isStatic(method.getModifiers())) {
                    throw new IllegalArgumentException("All command methods must be static!");
                }
                this.name = name;
                this.aliases = aliases;
                this.method = method;
                this.parameterTypes = method.getParameters().clone();
                this.parent = parent;
                if (Modifier.isPrivate(method.getModifiers()) || Modifier.isProtected(method.getModifiers())) {
                    method.setAccessible(true);
                }
            }

            @Override
            public String toString() {
                return "InternalCommandInvoker{" +
                        "name='" + name + '\'' +
                        ", aliases=" + Arrays.toString(aliases) +
                        ", method=" + method +
                        ", parameterTypes=" + Arrays.toString(parameterTypes) +
                        '}';
            }
        }
    }
}