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

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