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 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. /*
  2. * Copyright (c) 2006-2011 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.CommandManager;
  31. import com.dmdirc.commandparser.CommandType;
  32. import com.dmdirc.commandparser.commands.Command;
  33. import com.dmdirc.commandparser.commands.CommandOptions;
  34. import com.dmdirc.commandparser.commands.ExternalCommand;
  35. import com.dmdirc.commandparser.commands.PreviousCommand;
  36. import com.dmdirc.config.IdentityManager;
  37. import com.dmdirc.util.collections.RollingList;
  38. import java.io.Serializable;
  39. import java.util.HashMap;
  40. import java.util.Map;
  41. /**
  42. * Represents a generic command parser. A command parser takes a line of input
  43. * from the user, determines if it is an attempt at executing a command (based
  44. * on the character at the start of the string), and handles it appropriately.
  45. */
  46. public abstract class CommandParser implements Serializable {
  47. /**
  48. * A version number for this class. It should be changed whenever the class
  49. * structure is changed (or anything else that would prevent serialized
  50. * objects being unserialized with the new class).
  51. */
  52. private static final long serialVersionUID = 1;
  53. /**
  54. * Commands that are associated with this parser.
  55. */
  56. private final Map<String, CommandInfoPair> commands;
  57. /**
  58. * A history of commands that have been entered into this parser.
  59. */
  60. private final RollingList<PreviousCommand> history;
  61. /** Command manager to use. */
  62. protected final CommandManager commandManager = CommandManager.getCommandManager();
  63. /** Creates a new instance of CommandParser. */
  64. protected CommandParser() {
  65. commands = new HashMap<String, CommandInfoPair>();
  66. history = new RollingList<PreviousCommand>(
  67. IdentityManager.getGlobalConfig().getOptionInt("general",
  68. "commandhistory"));
  69. loadCommands();
  70. }
  71. /**
  72. * Sets the owner of this command parser.
  73. *
  74. * @param owner The container which owns this parser
  75. * @since 0.6.4
  76. */
  77. public abstract void setOwner(final FrameContainer owner);
  78. /** Loads the relevant commands into the parser. */
  79. protected abstract void loadCommands();
  80. /**
  81. * Registers the specified command with this parser.
  82. *
  83. * @since 0.6.3m1
  84. * @param command Command to be registered
  85. * @param info The information the command should be registered with
  86. */
  87. public final void registerCommand(final Command command, final CommandInfo info) {
  88. commands.put(info.getName().toLowerCase(), new CommandInfoPair(info, command));
  89. }
  90. /**
  91. * Unregisters the specified command with this parser.
  92. *
  93. * @param info Command information to be unregistered
  94. * @since 0.6.3m1
  95. */
  96. public final void unregisterCommand(final CommandInfo info) {
  97. commands.remove(info.getName().toLowerCase());
  98. }
  99. /**
  100. * Retrieves a map of commands known by this command parser.
  101. *
  102. * @since 0.6.3m1
  103. * @return A map of commands known to this parser
  104. */
  105. public Map<String, CommandInfoPair> getCommands() {
  106. return new HashMap<String, CommandInfoPair>(commands);
  107. }
  108. /**
  109. * Parses the specified string as a command.
  110. *
  111. * @param origin The container which received the command
  112. * @param line The line to be parsed
  113. * @param parseChannel Whether or not to try and parse the first argument
  114. * as a channel name
  115. * @since 0.6.4
  116. */
  117. public final void parseCommand(final FrameContainer origin,
  118. final String line, final boolean parseChannel) {
  119. final CommandArguments args = new CommandArguments(line);
  120. if (args.isCommand()) {
  121. if (handleChannelCommand(origin, args, parseChannel)) {
  122. return;
  123. }
  124. if (commands.containsKey(args.getCommandName().toLowerCase())) {
  125. final CommandInfoPair pair = commands.get(args.getCommandName().toLowerCase());
  126. addHistory(args.getStrippedLine());
  127. executeCommand(origin, pair.getCommandInfo(), pair.getCommand(), args);
  128. } else {
  129. handleInvalidCommand(origin, args);
  130. }
  131. } else {
  132. handleNonCommand(origin, line);
  133. }
  134. }
  135. /**
  136. * Checks to see whether the inputted command is a channel or external
  137. * command, and if it is whether one or more channels have been specified
  138. * for its execution. If it is a channel or external command, and channels
  139. * are specified, this method invoke the appropriate command parser methods
  140. * to handle the command, and will return true. If the command is not
  141. * handled, the method returns false.
  142. *
  143. * @param origin The container which received the command
  144. * @param args The command and its arguments
  145. * @param parseChannel Whether or not to try parsing channel names
  146. * @return True iff the command was handled, false otherwise
  147. */
  148. protected boolean handleChannelCommand(final FrameContainer origin,
  149. final CommandArguments args, final boolean parseChannel) {
  150. final boolean silent = args.isSilent();
  151. final String command = args.getCommandName();
  152. final String[] cargs = args.getArguments();
  153. if (cargs.length == 0 || !parseChannel || origin == null
  154. || origin.getServer() == null
  155. || !commandManager.isChannelCommand(command)) {
  156. return false;
  157. }
  158. final Server server = origin.getServer();
  159. final String[] parts = cargs[0].split(",");
  160. boolean someValid = false;
  161. for (String part : parts) {
  162. someValid |= server.isValidChannelName(part);
  163. }
  164. if (someValid) {
  165. for (String channel : parts) {
  166. if (!server.isValidChannelName(channel)) {
  167. origin.addLine("commandError", "Invalid channel name: " + channel);
  168. continue;
  169. }
  170. if (server.hasChannel(channel)) {
  171. server.getChannel(channel).getCommandParser()
  172. .parseCommand(origin, commandManager.getCommandChar()
  173. + args.getCommandName() + " " + args.getWordsAsString(2), false);
  174. } else {
  175. final Map.Entry<CommandInfo, Command> actCommand
  176. = commandManager.getCommand(CommandType.TYPE_CHANNEL, command);
  177. if (actCommand != null && actCommand.getValue() instanceof ExternalCommand) {
  178. ((ExternalCommand) actCommand.getValue()).execute(
  179. origin, server, channel, silent,
  180. new CommandArguments(args.getCommandName()
  181. + " " + args.getWordsAsString(2)));
  182. }
  183. }
  184. }
  185. return true;
  186. }
  187. return false;
  188. }
  189. /**
  190. * Adds a command to this parser's history.
  191. *
  192. * @param command The command name and arguments that were used
  193. */
  194. private void addHistory(final String command) {
  195. synchronized(history) {
  196. final PreviousCommand pc = new PreviousCommand(command);
  197. history.remove(pc);
  198. history.add(pc);
  199. }
  200. }
  201. /**
  202. * Retrieves the most recent time that the specified command was used.
  203. * Commands should not include command or silence chars.
  204. *
  205. * @param command The command to search for
  206. * @return The timestamp that the command was used, or 0 if it wasn't
  207. */
  208. public long getCommandTime(final String command) {
  209. long res = 0;
  210. synchronized(history) {
  211. for (PreviousCommand pc : history.getList()) {
  212. if (pc.getLine().matches("(?i)" + command)) {
  213. res = Math.max(res, pc.getTime());
  214. }
  215. }
  216. }
  217. return res;
  218. }
  219. /**
  220. * Parses the specified string as a command.
  221. *
  222. * @param origin The container which received the command
  223. * @param line The line to be parsed
  224. * @since 0.6.4
  225. */
  226. public final void parseCommand(final FrameContainer origin,
  227. final String line) {
  228. parseCommand(origin, line, true);
  229. }
  230. /**
  231. * Handles the specified string as a non-command.
  232. *
  233. * @param origin The window in which the command was typed
  234. * @param line The line to be parsed
  235. */
  236. public final void parseCommandCtrl(final FrameContainer origin, final String line) {
  237. handleNonCommand(origin, line);
  238. }
  239. /**
  240. * Executes the specified command with the given arguments.
  241. *
  242. * @param origin The container which received the command
  243. * @param commandInfo The command information object matched by the command
  244. * @param command The command to be executed
  245. * @param args The arguments to the command
  246. * @since 0.6.4
  247. */
  248. protected abstract void executeCommand(final FrameContainer origin,
  249. final CommandInfo commandInfo, final Command command,
  250. final CommandArguments args);
  251. /**
  252. * Called when the user attempted to issue a command (i.e., used the command
  253. * character) that wasn't found. It could be that the command has a different
  254. * arity, or that it plain doesn't exist.
  255. *
  256. * @param origin The window in which the command was typed
  257. * @param args The arguments passed to the command
  258. * @since 0.6.3m1
  259. */
  260. protected void handleInvalidCommand(final FrameContainer origin,
  261. final CommandArguments args) {
  262. if (origin == null) {
  263. ActionManager.getActionManager().triggerEvent(
  264. CoreActionType.UNKNOWN_COMMAND, null, null,
  265. args.getCommandName(), args.getArguments());
  266. } else {
  267. final StringBuffer buff = new StringBuffer("unknownCommand");
  268. ActionManager.getActionManager().triggerEvent(
  269. CoreActionType.UNKNOWN_COMMAND, buff, origin,
  270. args.getCommandName(), args.getArguments());
  271. origin.addLine(buff, args.getCommandName());
  272. }
  273. }
  274. /**
  275. * Called when the input was a line of text that was not a command. This normally
  276. * means it is sent to the server/channel/user as-is, with no further processing.
  277. *
  278. * @param origin The window in which the command was typed
  279. * @param line The line input by the user
  280. */
  281. protected abstract void handleNonCommand(final FrameContainer origin,
  282. final String line);
  283. /**
  284. * Determines if the specified command has defined any command options.
  285. *
  286. * @param command The command to investigate
  287. * @return True if the command defines options, false otherwise
  288. */
  289. protected boolean hasCommandOptions(final Command command) {
  290. return command.getClass().isAnnotationPresent(CommandOptions.class);
  291. }
  292. /**
  293. * Retrieves the command options for the specified command. If the command
  294. * does not define options, this method will return null.
  295. *
  296. * @param command The command whose options should be retrieved
  297. * @return The command's options, or null if not available
  298. */
  299. protected CommandOptions getCommandOptions(final Command command) {
  300. return command.getClass().getAnnotation(CommandOptions.class);
  301. }
  302. }