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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. /*
  2. * Copyright (c) 2006-2009 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.Server;
  24. import com.dmdirc.actions.ActionManager;
  25. import com.dmdirc.actions.CoreActionType;
  26. import com.dmdirc.commandparser.CommandInfo;
  27. import com.dmdirc.commandparser.CommandManager;
  28. import com.dmdirc.commandparser.CommandType;
  29. import com.dmdirc.commandparser.commands.Command;
  30. import com.dmdirc.commandparser.commands.ExternalCommand;
  31. import com.dmdirc.commandparser.commands.PreviousCommand;
  32. import com.dmdirc.config.IdentityManager;
  33. import com.dmdirc.ui.interfaces.InputWindow;
  34. import com.dmdirc.util.RollingList;
  35. import java.io.Serializable;
  36. import java.util.Hashtable;
  37. import java.util.Map;
  38. /**
  39. * Represents a generic command parser. A command parser takes a line of input
  40. * from the user, determines if it is an attempt at executing a command (based
  41. * on the character at the start of the string), and handles it appropriately.
  42. *
  43. * @author chris
  44. */
  45. public abstract class CommandParser implements Serializable {
  46. /**
  47. * A version number for this class. It should be changed whenever the class
  48. * structure is changed (or anything else that would prevent serialized
  49. * objects being unserialized with the new class).
  50. */
  51. private static final long serialVersionUID = 1;
  52. /**
  53. * Commands that are associated with this parser.
  54. */
  55. private final Map<String, Command> commands;
  56. /**
  57. * A history of commands that have been entered into this parser.
  58. */
  59. private final RollingList<PreviousCommand> history;
  60. /** Creates a new instance of CommandParser. */
  61. public CommandParser() {
  62. commands = new Hashtable<String, Command>();
  63. history = new RollingList<PreviousCommand>(
  64. IdentityManager.getGlobalConfig().getOptionInt("general",
  65. "commandhistory"));
  66. loadCommands();
  67. }
  68. /** Loads the relevant commands into the parser. */
  69. protected abstract void loadCommands();
  70. /**
  71. * Registers the specified command with this parser.
  72. *
  73. * @since 0.6.3
  74. * @param command Command to be registered
  75. * @param info The information the command should be registered with
  76. */
  77. public final void registerCommand(final Command command, final CommandInfo info) {
  78. commands.put(info.getName().toLowerCase(), command);
  79. }
  80. /**
  81. * Unregisters the specified command with this parser.
  82. *
  83. * @param info Command information to be unregistered
  84. * @since 0.6.3
  85. */
  86. public final void unregisterCommand(final CommandInfo info) {
  87. commands.remove(info.getName().toLowerCase());
  88. }
  89. /**
  90. * Parses the specified string as a command.
  91. *
  92. * @param origin The window in which the command was typed
  93. * @param line The line to be parsed
  94. * @param parseChannel Whether or not to try and parse the first argument
  95. * as a channel name
  96. */
  97. public final void parseCommand(final InputWindow origin,
  98. final String line, final boolean parseChannel) {
  99. if (line.isEmpty()) {
  100. return;
  101. }
  102. if (line.charAt(0) == CommandManager.getCommandChar()) {
  103. int offset = 1;
  104. boolean silent = false;
  105. if (line.length() > offset && line.charAt(offset) == CommandManager.getSilenceChar()) {
  106. silent = true;
  107. offset++;
  108. }
  109. final String[] args = line.split(" ");
  110. final String command = args[0].substring(offset);
  111. String[] comargs;
  112. if (args.length >= 2 && parseChannel && origin != null
  113. && origin.getContainer() != null
  114. && origin.getContainer().getServer() != null
  115. && origin.getContainer().getServer().isValidChannelName(args[1])
  116. && CommandManager.isChannelCommand(command)) {
  117. final Server server = origin.getContainer().getServer();
  118. if (server.hasChannel(args[1])) {
  119. final StringBuilder newLine = new StringBuilder();
  120. for (int i = 0; i < args.length; i++) {
  121. if (i == 1) { continue; }
  122. newLine.append(" ").append(args[i]);
  123. }
  124. server.getChannel(args[1]).getFrame().getCommandParser()
  125. .parseCommand(origin, newLine.substring(1), false);
  126. return;
  127. } else {
  128. final Command actCommand = CommandManager.getCommand(
  129. CommandType.TYPE_CHANNEL, command);
  130. if (actCommand instanceof ExternalCommand) {
  131. comargs = new String[args.length - 2];
  132. System.arraycopy(args, 2, comargs, 0, args.length - 2);
  133. ((ExternalCommand) actCommand).execute(origin, server,
  134. args[1], silent, comargs);
  135. return;
  136. }
  137. }
  138. }
  139. comargs = new String[args.length - 1];
  140. System.arraycopy(args, 1, comargs, 0, args.length - 1);
  141. final String signature = command;
  142. if (commands.containsKey(signature.toLowerCase())) {
  143. addHistory(line.substring(offset));
  144. executeCommand(origin, silent, commands.get(signature.toLowerCase()), comargs);
  145. } else {
  146. handleInvalidCommand(origin, command, comargs);
  147. }
  148. } else {
  149. handleNonCommand(origin, line);
  150. }
  151. }
  152. /**
  153. * Adds a command to this parser's history.
  154. *
  155. * @param command The command name and arguments that were used
  156. */
  157. private void addHistory(final String command) {
  158. synchronized(history) {
  159. final PreviousCommand pc = new PreviousCommand(command);
  160. history.remove(pc);
  161. history.add(pc);
  162. }
  163. }
  164. /**
  165. * Retrieves the most recent time that the specified command was used.
  166. * Commands should not include command or silence chars.
  167. *
  168. * @param command The command to search for
  169. * @return The timestamp that the command was used, or 0 if it wasn't
  170. */
  171. public long getCommandTime(final String command) {
  172. long res = 0;
  173. synchronized(history) {
  174. for (PreviousCommand pc : history.getList()) {
  175. if (pc.getLine().matches("(?i)" + command)) {
  176. res = Math.max(res, pc.getTime());
  177. }
  178. }
  179. }
  180. return res;
  181. }
  182. /**
  183. * Parses the specified string as a command.
  184. *
  185. * @param origin The window in which the command was typed
  186. * @param line The line to be parsed
  187. */
  188. public final void parseCommand(final InputWindow origin,
  189. final String line) {
  190. parseCommand(origin, line, true);
  191. }
  192. /**
  193. * Handles the specified string as a non-command.
  194. *
  195. * @param origin The window in which the command was typed
  196. * @param line The line to be parsed
  197. */
  198. public final void parseCommandCtrl(final InputWindow origin, final String line) {
  199. handleNonCommand(origin, line);
  200. }
  201. /**
  202. * Executes the specified command with the given arguments.
  203. *
  204. * @param origin The window in which the command was typed
  205. * @param isSilent Whether the command is being silenced or not
  206. * @param command The command to be executed
  207. * @param args The arguments to the command
  208. */
  209. protected abstract void executeCommand(final InputWindow origin,
  210. final boolean isSilent, final Command command, final String... args);
  211. /**
  212. * Called when the user attempted to issue a command (i.e., used the command
  213. * character) that wasn't found. It could be that the command has a different
  214. * arity, or that it plain doesn't exist.
  215. * @param origin The window in which the command was typed
  216. * @param command The command the user tried to execute
  217. * @param args The arguments passed to the command
  218. */
  219. protected void handleInvalidCommand(final InputWindow origin,
  220. final String command, final String... args) {
  221. if (origin == null) {
  222. ActionManager.processEvent(CoreActionType.UNKNOWN_COMMAND, null,
  223. null, command, args);
  224. } else {
  225. final StringBuffer buff = new StringBuffer("unknownCommand");
  226. ActionManager.processEvent(CoreActionType.UNKNOWN_COMMAND, buff,
  227. origin.getContainer(), command, args);
  228. origin.addLine(buff, command);
  229. }
  230. }
  231. /**
  232. * Called when the input was a line of text that was not a command. This normally
  233. * means it is sent to the server/channel/user as-is, with no further processing.
  234. *
  235. * @param origin The window in which the command was typed
  236. * @param line The line input by the user
  237. */
  238. protected abstract void handleNonCommand(final InputWindow origin,
  239. final String line);
  240. }