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.

ActionSubstitutor.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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.actions;
  23. import com.dmdirc.FrameContainer;
  24. import com.dmdirc.Precondition;
  25. import com.dmdirc.ServerState;
  26. import com.dmdirc.commandparser.CommandArguments;
  27. import com.dmdirc.interfaces.ActionController;
  28. import com.dmdirc.interfaces.CommandController;
  29. import com.dmdirc.interfaces.Connection;
  30. import com.dmdirc.interfaces.actions.ActionComponent;
  31. import com.dmdirc.interfaces.actions.ActionType;
  32. import com.dmdirc.interfaces.config.AggregateConfigProvider;
  33. import com.dmdirc.interfaces.ui.Window;
  34. import java.util.Arrays;
  35. import java.util.HashMap;
  36. import java.util.Map;
  37. import java.util.Set;
  38. import java.util.regex.Matcher;
  39. import java.util.regex.Pattern;
  40. /**
  41. * Handles the substitution of variables into action targets and responses.
  42. */
  43. public class ActionSubstitutor {
  44. /** Substitution to use when a component requires a connected server. */
  45. private static final String ERR_NOT_CONNECTED = "not_connected";
  46. /** Substitution to use to replace an unknown substitution. */
  47. private static final String ERR_NOT_DEFINED = "not_defined";
  48. /** Substitution to use to replace a chain that evaluates to null. */
  49. private static final String ERR_NULL_CHAIN = "null_component";
  50. /** Substitution to use to replace subs with illegal components. */
  51. private static final String ERR_ILLEGAL_COMPONENT = "illegal_component";
  52. /** Pattern used to match braced substitutions. */
  53. private static final Pattern BRACES_PATTERN = Pattern.compile("(?<!\\\\)((?:\\\\\\\\)*)"
  54. + "(\\$\\{([^{}]*?)\\})");
  55. /** Pattern used to match all other substitutions. */
  56. private static final Pattern OTHER_PATTERN = Pattern.compile("(?<!\\\\)((?:\\\\\\\\)*)(\\$("
  57. + "[0-9]+(-([0-9]+)?)?|" // Word subs - $1, $1-, $1-2
  58. + "[0-9]+(\\.([A-Z_]+))+|" // Component subs - 2.FOO_BAR
  59. + "[a-z0-9A-Z_\\.]+" // Config/server subs
  60. + "))");
  61. /** Pattern to determine if a substitution is a word number type. */
  62. private static final Pattern NUMBER_PATTERN = Pattern.compile("([0-9]+)(-([0-9]+)?)?");
  63. /** Pattern to determine if a substitution is an argument+component type. */
  64. private static final Pattern COMP_PATTERN = Pattern.compile("([0-9]+)\\.([A-Z_]+(\\.[A-Z_]+)*)");
  65. /** Pattern to determine if a substitution is a server component type. */
  66. private static final Pattern SERVER_PATTERN = Pattern.compile("[A-Z_]+(\\.[A-Z_]+)*");
  67. /** The action controller to use to find components. */
  68. private final ActionController actionController;
  69. /** The global config to read settings from. */
  70. private final AggregateConfigProvider globalConfig;
  71. /** The command controller to use when building command arguments. */
  72. private final CommandController commandController;
  73. /** The action type this substitutor is for. */
  74. private final ActionType type;
  75. /**
  76. * Creates a new substitutor for the specified action type.
  77. *
  78. * @param actionController The action controller to use to find components.
  79. * @param commandController The command controller to use when building command arguments.
  80. * @param globalConfig The global config to read settings from.
  81. * @param type The action type this substitutor is for
  82. */
  83. public ActionSubstitutor(
  84. final ActionController actionController,
  85. final CommandController commandController,
  86. final AggregateConfigProvider globalConfig,
  87. final ActionType type) {
  88. this.actionController = actionController;
  89. this.globalConfig = globalConfig;
  90. this.commandController = commandController;
  91. this.type = type;
  92. }
  93. /**
  94. * Retrieves a list of global config variables that will be substituted. Note: does not include
  95. * initial $.
  96. *
  97. * @return A list of global variable names that will be substituted
  98. */
  99. public Set<String> getConfigSubstitutions() {
  100. return globalConfig.getOptions("actions").keySet();
  101. }
  102. /**
  103. * Retrieves a list of substitutions derived from argument and component combinations, along
  104. * with a corresponding friendly name for them. Note: does not include initial $.
  105. *
  106. * @return A map of component substitution names and their descriptions
  107. */
  108. public Map<String, String> getComponentSubstitutions() {
  109. final Map<String, String> res = new HashMap<>();
  110. int i = 0;
  111. for (Class<?> myClass : type.getType().getArgTypes()) {
  112. for (ActionComponent comp : actionController.findCompatibleComponents(myClass)) {
  113. final String key = "{" + i + "." + comp.toString() + "}";
  114. final String desc = type.getType().getArgNames()[i] + "'s " + comp.getName();
  115. res.put(key, desc);
  116. }
  117. i++;
  118. }
  119. return res;
  120. }
  121. /**
  122. * Retrieves a list of server substitutions, if this action type supports them. Note: does not
  123. * include initial $.
  124. *
  125. * @return A map of server substitution names and their descriptions.
  126. */
  127. public Map<String, String> getServerSubstitutions() {
  128. final Map<String, String> res = new HashMap<>();
  129. if (hasFrameContainer()) {
  130. for (ActionComponent comp : actionController
  131. .findCompatibleComponents(Connection.class)) {
  132. final String key = "{" + comp.toString() + "}";
  133. final String desc = "The connection's " + comp.getName();
  134. res.put(key, desc);
  135. }
  136. }
  137. return res;
  138. }
  139. /**
  140. * Returns true if this action type's first argument is a frame container, or descendant of one.
  141. *
  142. * @return True if this action type's first arg extends or is a FrameContainer
  143. */
  144. private boolean hasFrameContainer() {
  145. Class<?> target = null;
  146. if (type.getType().getArgTypes().length > 0) {
  147. target = type.getType().getArgTypes()[0];
  148. while (target != null && target != FrameContainer.class) {
  149. target = target.getSuperclass();
  150. }
  151. }
  152. return target == FrameContainer.class;
  153. }
  154. /**
  155. * Determines whether or not word substitutions will work for this action type. Word
  156. * substitutions take the form $1, $1-5, $6-, etc.
  157. *
  158. * @return True if word substitutions are supported, false otherwise.
  159. */
  160. public boolean usesWordSubstitutions() {
  161. return type.getType().getArgTypes().length > 2
  162. && (type.getType().getArgTypes()[2] == String[].class
  163. || type.getType().getArgTypes()[2] == String.class);
  164. }
  165. /**
  166. * Performs all applicable substitutions on the specified string, with the specified arguments.
  167. *
  168. * @param target The string to be altered
  169. * @param args The arguments for the action type
  170. *
  171. * @return The substituted string
  172. */
  173. @Precondition("Number of arguments given equals the number of arguments "
  174. + "required by this substitutor's type")
  175. public String doSubstitution(final String target, final Object... args) {
  176. if (type.getType().getArity() != args.length) {
  177. throw new IllegalArgumentException("Invalid number of arguments "
  178. + "for doSubstitution: expected " + type.getType().getArity() + ", got "
  179. + args.length + ". Type: " + type.getName());
  180. }
  181. final StringBuilder res = new StringBuilder(target);
  182. Matcher bracesMatcher = BRACES_PATTERN.matcher(res);
  183. Matcher otherMatcher = OTHER_PATTERN.matcher(res);
  184. boolean first;
  185. while ((first = bracesMatcher.find()) || otherMatcher.find()) {
  186. final Matcher matcher = first ? bracesMatcher : otherMatcher;
  187. final String group = matcher.group(3);
  188. final int start = matcher.start() + matcher.group(1).length();
  189. final int end = matcher.end();
  190. res.delete(start, end);
  191. res.insert(start, getSubstitution(doSubstitution(group, args), args));
  192. bracesMatcher = BRACES_PATTERN.matcher(res);
  193. otherMatcher = OTHER_PATTERN.matcher(res);
  194. }
  195. return res.toString().replaceAll("\\\\(.)", "$1");
  196. }
  197. /**
  198. * Retrieves the value which should be used for the specified substitution.
  199. *
  200. * @param substitution The substitution, without leading $
  201. * @param args The arguments for the action
  202. *
  203. * @return The substitution to be used
  204. */
  205. private String getSubstitution(final String substitution, final Object... args) {
  206. final Matcher numberMatcher = NUMBER_PATTERN.matcher(substitution);
  207. final Matcher compMatcher = COMP_PATTERN.matcher(substitution);
  208. final Matcher serverMatcher = SERVER_PATTERN.matcher(substitution);
  209. if (usesWordSubstitutions() && numberMatcher.matches()) {
  210. final CommandArguments words = args[2] instanceof String
  211. ? new CommandArguments(commandController, (String) args[2])
  212. : new CommandArguments(commandController, Arrays.asList((String[]) args[2]));
  213. final int start;
  214. int end;
  215. start = end = Integer.parseInt(numberMatcher.group(1)) - 1;
  216. if (numberMatcher.group(3) != null) {
  217. end = Integer.parseInt(numberMatcher.group(3)) - 1;
  218. } else if (numberMatcher.group(2) != null) {
  219. end = words.getWords().length - 1;
  220. }
  221. return words.getWordsAsString(start, end);
  222. }
  223. if (compMatcher.matches()) {
  224. final int argument = Integer.parseInt(compMatcher.group(1));
  225. try {
  226. final ActionComponentChain chain = new ActionComponentChain(
  227. type.getType().getArgTypes()[argument], compMatcher.group(2),
  228. actionController);
  229. return escape(checkConnection(chain, args, args[argument]));
  230. } catch (IllegalArgumentException ex) {
  231. return ERR_ILLEGAL_COMPONENT;
  232. }
  233. }
  234. final AggregateConfigProvider manager = getConfigManager(args);
  235. if (manager.hasOptionString("actions", substitution)) {
  236. return manager.getOption("actions", substitution);
  237. }
  238. if (hasFrameContainer() && serverMatcher.matches()) {
  239. final Connection connection = ((FrameContainer) args[0]).getConnection();
  240. if (connection != null) {
  241. try {
  242. final ActionComponentChain chain = new ActionComponentChain(
  243. Connection.class, substitution, actionController);
  244. return escape(checkConnection(chain, args, connection));
  245. } catch (IllegalArgumentException ex) {
  246. return ERR_ILLEGAL_COMPONENT;
  247. }
  248. }
  249. }
  250. return ERR_NOT_DEFINED;
  251. }
  252. /**
  253. * Checks the connection status of any server associated with the specified arguments. If the
  254. * specified component chain requires a server with an established connection and no such server
  255. * is present, this method returns the string {@code not_connected} without attempting to
  256. * evaluate any components in the chain.
  257. *
  258. * @since 0.6.4
  259. * @param chain The chain to be checked
  260. * @param args The arguments for this invocation
  261. * @param argument The argument used as a base for the chain
  262. *
  263. * @return The value of the evaluated chain, or <code>not_connected</code>
  264. */
  265. protected String checkConnection(final ActionComponentChain chain,
  266. final Object[] args, final Object argument) {
  267. if ((chain.requiresConnection() && args[0] instanceof FrameContainer
  268. && ((FrameContainer) args[0]).getConnection().getState()
  269. == ServerState.CONNECTED) || !chain.requiresConnection()) {
  270. final Object res = chain.get(argument);
  271. return res == null ? ERR_NULL_CHAIN : res.toString();
  272. }
  273. return ERR_NOT_CONNECTED;
  274. }
  275. /**
  276. * Tries to retrieve an appropriate configuration manager from the specified set of arguments.
  277. * If any of the arguments is an instance of {@link FrameContainer} or {@link Window}, the
  278. * config manager is requested from them. Otherwise, the global config is returned.
  279. *
  280. * @param args The arguments to be tested
  281. *
  282. * @return The best config manager to use for those arguments
  283. *
  284. * @since 0.6.3m2
  285. */
  286. protected AggregateConfigProvider getConfigManager(final Object... args) {
  287. for (Object arg : args) {
  288. if (arg instanceof FrameContainer) {
  289. return ((FrameContainer) arg).getConfigManager();
  290. } else if (arg instanceof Window) {
  291. return ((Window) arg).getContainer().getConfigManager();
  292. }
  293. }
  294. return globalConfig;
  295. }
  296. /**
  297. * Escapes all special characters in the specified input. This will result in the input being
  298. * treated as a plain string when passed through the substitutor (i.e., no substitutions will
  299. * occur).
  300. *
  301. * @param input The string to be escaped
  302. *
  303. * @return An escaped version of the specified string
  304. *
  305. * @since 0.6.4
  306. */
  307. protected static String escape(final String input) {
  308. return input.replace("\\", "\\\\").replace("$", "\\$");
  309. }
  310. }