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

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