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

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