You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CommandParser.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. /*
  2. * Copyright (c) 2006-2014 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.commandparser.parsers;
  23. import com.dmdirc.FrameContainer;
  24. import com.dmdirc.Server;
  25. import com.dmdirc.actions.ActionManager;
  26. import com.dmdirc.actions.CoreActionType;
  27. import com.dmdirc.commandparser.CommandArguments;
  28. import com.dmdirc.commandparser.CommandInfo;
  29. import com.dmdirc.commandparser.CommandInfoPair;
  30. import com.dmdirc.commandparser.CommandType;
  31. import com.dmdirc.commandparser.commands.Command;
  32. import com.dmdirc.commandparser.commands.CommandOptions;
  33. import com.dmdirc.commandparser.commands.ExternalCommand;
  34. import com.dmdirc.commandparser.commands.PreviousCommand;
  35. import com.dmdirc.commandparser.commands.context.CommandContext;
  36. import com.dmdirc.interfaces.CommandController;
  37. import com.dmdirc.interfaces.Connection;
  38. import com.dmdirc.interfaces.config.AggregateConfigProvider;
  39. import com.dmdirc.util.collections.RollingList;
  40. import java.io.Serializable;
  41. import java.util.HashMap;
  42. import java.util.Map;
  43. import javax.annotation.Nonnull;
  44. import static com.google.common.base.Preconditions.checkNotNull;
  45. /**
  46. * Represents a generic command parser. A command parser takes a line of input from the user,
  47. * determines if it is an attempt at executing a command (based on the character at the start of the
  48. * string), and handles it appropriately.
  49. */
  50. public abstract class CommandParser implements Serializable {
  51. /** A version number for this class. */
  52. private static final long serialVersionUID = 1;
  53. /** Commands that are associated with this parser. */
  54. private final Map<String, CommandInfoPair> commands;
  55. /** A history of commands that have been entered into this parser. */
  56. private final RollingList<PreviousCommand> history;
  57. /** Command manager to use. */
  58. protected final CommandController commandManager;
  59. /**
  60. * Creates a new instance of CommandParser.
  61. *
  62. * @param configManager Config manager to read settings
  63. * @param commandManager Command manager to load plugins from
  64. */
  65. protected CommandParser(final AggregateConfigProvider configManager,
  66. final CommandController commandManager) {
  67. commands = new HashMap<>();
  68. history = new RollingList<>(configManager.getOptionInt("general", "commandhistory"));
  69. this.commandManager = commandManager;
  70. loadCommands();
  71. }
  72. /**
  73. * @deprecated Callers should obtain their own instance of command controller.
  74. */
  75. @Deprecated
  76. public CommandController getCommandManager() {
  77. return commandManager;
  78. }
  79. /**
  80. * Sets the owner of this command parser.
  81. *
  82. * @param owner The container which owns this parser
  83. *
  84. * @since 0.6.4
  85. */
  86. public abstract void setOwner(final FrameContainer owner);
  87. /** Loads the relevant commands into the parser. */
  88. protected abstract void loadCommands();
  89. /**
  90. * Registers the specified command with this parser.
  91. *
  92. * @since 0.6.3m1
  93. * @param command Command to be registered
  94. * @param info The information the command should be registered with
  95. */
  96. public final void registerCommand(final Command command, final CommandInfo info) {
  97. commands.put(info.getName().toLowerCase(), new CommandInfoPair(info, command));
  98. }
  99. /**
  100. * Unregisters the specified command with this parser.
  101. *
  102. * @param info Command information to be unregistered
  103. *
  104. * @since 0.6.3m1
  105. */
  106. public final void unregisterCommand(final CommandInfo info) {
  107. commands.remove(info.getName().toLowerCase());
  108. }
  109. /**
  110. * Retrieves a map of commands known by this command parser.
  111. *
  112. * @since 0.6.3m1
  113. * @return A map of commands known to this parser
  114. */
  115. public Map<String, CommandInfoPair> getCommands() {
  116. return new HashMap<>(commands);
  117. }
  118. /**
  119. * Parses the specified string as a command.
  120. *
  121. * @param origin The container which received the command
  122. * @param line The line to be parsed
  123. * @param parseChannel Whether or not to try and parse the first argument as a channel name
  124. *
  125. * @since 0.6.4
  126. */
  127. public final void parseCommand(@Nonnull final FrameContainer origin, final String line,
  128. final boolean parseChannel) {
  129. checkNotNull(origin);
  130. final CommandArguments args = new CommandArguments(commandManager, line);
  131. if (args.isCommand()) {
  132. if (handleChannelCommand(origin, args, parseChannel)) {
  133. return;
  134. }
  135. if (commands.containsKey(args.getCommandName().toLowerCase())) {
  136. final CommandInfoPair pair = commands.get(args.getCommandName().toLowerCase());
  137. addHistory(args.getStrippedLine());
  138. executeCommand(origin, pair.getCommandInfo(), pair.getCommand(), args,
  139. getCommandContext(origin, pair.getCommandInfo(), pair.getCommand(), args));
  140. } else {
  141. handleInvalidCommand(origin, args);
  142. }
  143. } else {
  144. handleNonCommand(origin, line);
  145. }
  146. }
  147. /**
  148. * Checks to see whether the inputted command is a channel or external command, and if it is
  149. * whether one or more channels have been specified for its execution. If it is a channel or
  150. * external command, and channels are specified, this method invoke the appropriate command
  151. * parser methods to handle the command, and will return true. If the command is not handled,
  152. * the method returns false.
  153. *
  154. * @param origin The container which received the command
  155. * @param args The command and its arguments
  156. * @param parseChannel Whether or not to try parsing channel names
  157. *
  158. * @return True iff the command was handled, false otherwise
  159. */
  160. protected boolean handleChannelCommand(@Nonnull final FrameContainer origin,
  161. final CommandArguments args, final boolean parseChannel) {
  162. final boolean silent = args.isSilent();
  163. final String command = args.getCommandName();
  164. final String[] cargs = args.getArguments();
  165. if (cargs.length == 0 || !parseChannel
  166. || origin.getConnection() == null
  167. || !commandManager.isChannelCommand(command)) {
  168. return false;
  169. }
  170. final Connection server = origin.getConnection();
  171. final String[] parts = cargs[0].split(",");
  172. boolean someValid = false;
  173. for (String part : parts) {
  174. someValid |= server.isValidChannelName(part);
  175. }
  176. if (someValid) {
  177. for (String channel : parts) {
  178. if (!server.isValidChannelName(channel)) {
  179. origin.addLine("commandError", "Invalid channel name: " + channel);
  180. continue;
  181. }
  182. final String newCommandString = commandManager.getCommandChar()
  183. + (silent ? String.valueOf(commandManager.getSilenceChar()) : "")
  184. + args.getCommandName()
  185. + (cargs.length > 1 ? " " + args.getArgumentsAsString(1) : "");
  186. if (server.hasChannel(channel)) {
  187. server.getChannel(channel).getCommandParser().parseCommand(origin,
  188. newCommandString, false);
  189. } else {
  190. final Map.Entry<CommandInfo, Command> actCommand = commandManager.getCommand(
  191. CommandType.TYPE_CHANNEL, command);
  192. if (actCommand != null && actCommand.getValue() instanceof ExternalCommand) {
  193. ((ExternalCommand) actCommand.getValue()).execute(
  194. origin, (Server) server, channel, silent,
  195. new CommandArguments(commandManager, newCommandString));
  196. }
  197. }
  198. }
  199. return true;
  200. }
  201. return false;
  202. }
  203. /**
  204. * Adds a command to this parser's history.
  205. *
  206. * @param command The command name and arguments that were used
  207. */
  208. private void addHistory(final String command) {
  209. synchronized (history) {
  210. final PreviousCommand pc = new PreviousCommand(command);
  211. history.remove(pc);
  212. history.add(pc);
  213. }
  214. }
  215. /**
  216. * Retrieves the most recent time that the specified command was used. Commands should not
  217. * include command or silence chars.
  218. *
  219. * @param command The command to search for
  220. *
  221. * @return The timestamp that the command was used, or 0 if it wasn't
  222. */
  223. public long getCommandTime(final String command) {
  224. long res = 0;
  225. synchronized (history) {
  226. for (PreviousCommand pc : history.getList()) {
  227. if (pc.getLine().matches("(?i)" + command)) {
  228. res = Math.max(res, pc.getTime());
  229. }
  230. }
  231. }
  232. return res;
  233. }
  234. /**
  235. * Parses the specified string as a command.
  236. *
  237. * @param origin The container which received the command
  238. * @param line The line to be parsed
  239. *
  240. * @since 0.6.4
  241. */
  242. public void parseCommand(@Nonnull final FrameContainer origin, final String line) {
  243. parseCommand(origin, line, true);
  244. }
  245. /**
  246. * Handles the specified string as a non-command.
  247. *
  248. * @param origin The window in which the command was typed
  249. * @param line The line to be parsed
  250. */
  251. public void parseCommandCtrl(final FrameContainer origin, final String line) {
  252. handleNonCommand(origin, line);
  253. }
  254. /**
  255. * Gets the context that the command will execute with.
  256. *
  257. * @param origin The container which received the command
  258. * @param commandInfo The command information object matched by the command
  259. * @param command The command to be executed
  260. * @param args The arguments to the command
  261. *
  262. * @return The context for the command.
  263. */
  264. protected abstract CommandContext getCommandContext(
  265. final FrameContainer origin,
  266. final CommandInfo commandInfo,
  267. final Command command,
  268. final CommandArguments args);
  269. /**
  270. * Executes the specified command with the given arguments.
  271. *
  272. * @param origin The container which received the command
  273. * @param commandInfo The command information object matched by the command
  274. * @param command The command to be executed
  275. * @param args The arguments to the command
  276. * @param context The context to use when executing the command
  277. */
  278. protected abstract void executeCommand(
  279. @Nonnull final FrameContainer origin,
  280. final CommandInfo commandInfo, final Command command,
  281. final CommandArguments args, final CommandContext context);
  282. /**
  283. * Called when the user attempted to issue a command (i.e., used the command character) that
  284. * wasn't found. It could be that the command has a different arity, or that it plain doesn't
  285. * exist.
  286. *
  287. * @param origin The window in which the command was typed
  288. * @param args The arguments passed to the command
  289. *
  290. * @since 0.6.3m1
  291. */
  292. protected void handleInvalidCommand(final FrameContainer origin,
  293. final CommandArguments args) {
  294. if (origin == null) {
  295. ActionManager.getActionManager().triggerEvent(
  296. CoreActionType.UNKNOWN_COMMAND, null, null,
  297. args.getCommandName(), args.getArguments());
  298. } else {
  299. final StringBuffer buff = new StringBuffer("unknownCommand");
  300. ActionManager.getActionManager().triggerEvent(
  301. CoreActionType.UNKNOWN_COMMAND, buff, origin,
  302. args.getCommandName(), args.getArguments());
  303. origin.addLine(buff, args.getCommandName());
  304. }
  305. }
  306. /**
  307. * Called when the input was a line of text that was not a command. This normally means it is
  308. * sent to the server/channel/user as-is, with no further processing.
  309. *
  310. * @param origin The window in which the command was typed
  311. * @param line The line input by the user
  312. */
  313. protected abstract void handleNonCommand(final FrameContainer origin,
  314. final String line);
  315. /**
  316. * Determines if the specified command has defined any command options.
  317. *
  318. * @param command The command to investigate
  319. *
  320. * @return True if the command defines options, false otherwise
  321. */
  322. protected boolean hasCommandOptions(final Command command) {
  323. return command.getClass().isAnnotationPresent(CommandOptions.class);
  324. }
  325. /**
  326. * Retrieves the command options for the specified command. If the command does not define
  327. * options, this method will return null.
  328. *
  329. * @param command The command whose options should be retrieved
  330. *
  331. * @return The command's options, or null if not available
  332. */
  333. protected CommandOptions getCommandOptions(final Command command) {
  334. return command.getClass().getAnnotation(CommandOptions.class);
  335. }
  336. }