Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. /*
  2. * Copyright (c) 2006-2007 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.actions;
  23. import com.dmdirc.FrameContainer;
  24. import com.dmdirc.ServerManager;
  25. import com.dmdirc.commandparser.CommandParser;
  26. import com.dmdirc.commandparser.GlobalCommandParser;
  27. import com.dmdirc.logger.ErrorLevel;
  28. import com.dmdirc.logger.Logger;
  29. import com.dmdirc.ui.interfaces.InputWindow;
  30. import com.dmdirc.ui.MainFrame;
  31. import java.io.File;
  32. import java.io.FileInputStream;
  33. import java.io.FileOutputStream;
  34. import java.io.IOException;
  35. import java.util.ArrayList;
  36. import java.util.List;
  37. import java.util.Properties;
  38. /**
  39. * Describes a single action.
  40. * @author chris
  41. */
  42. public class Action {
  43. /** The group this action belongs to. */
  44. private String group;
  45. /** The name of this action. */
  46. private String name;
  47. /** The file containing this action. */
  48. private final File file;
  49. /** The properties read for this action. */
  50. private Properties properties;
  51. /** The ActionTypes that trigger this action. */
  52. private ActionType[] triggers;
  53. /** The commands to execute if this action is triggered. */
  54. private String[] response;
  55. /** The change that should be made to the format string, if any. */
  56. private String newFormat = null;
  57. /** The conditions for this action. */
  58. private List<ActionCondition> conditions = new ArrayList<ActionCondition>();
  59. /**
  60. * Creates a new instance of Action. The group and name specified must
  61. * be the group and name of a valid action already saved to disk.
  62. * @param group The group the action belongs to
  63. * @param name The name of the action
  64. */
  65. public Action(final String group, final String name) {
  66. this.group = group;
  67. this.name = name;
  68. final String fs = System.getProperty("file.separator");
  69. final String location = ActionManager.getDirectory() + group + fs + name;
  70. file = new File(location);
  71. try {
  72. final FileInputStream inputStream = new FileInputStream(file);
  73. properties = new Properties();
  74. properties.load(inputStream);
  75. loadAction();
  76. inputStream.close();
  77. } catch (IOException ex) {
  78. Logger.error(ErrorLevel.ERROR, "Unable to load action: " + group + "/" + name, ex);
  79. }
  80. }
  81. /**
  82. * Creates a new instance of Action with the specified properties and saves
  83. * it to disk.
  84. * @param group The group the action belongs to
  85. * @param name The name of the action
  86. * @param triggers The triggers to use
  87. * @param response The response to use
  88. * @param conditions The conditions to use
  89. * @param newFormat The new formatter to use
  90. */
  91. public Action(final String group, final String name,
  92. final ActionType[] triggers, final String[] response,
  93. final List<ActionCondition> conditions, final String newFormat) {
  94. this.group = group;
  95. this.name = name;
  96. this.triggers = triggers.clone();
  97. this.response = response.clone();
  98. this.conditions = conditions;
  99. this.newFormat = newFormat;
  100. final String fs = System.getProperty("file.separator");
  101. final String location = ActionManager.getDirectory() + group + fs + name;
  102. file = new File(location);
  103. save();
  104. ActionManager.registerAction(this);
  105. }
  106. /**
  107. * Loads the various attributes of this action from the properties instance.
  108. */
  109. private void loadAction() {
  110. // Read the triggers
  111. if (properties.containsKey("trigger")) {
  112. final String[] triggerStrings = properties.getProperty("trigger").split("\\|");
  113. Class[] args = null;
  114. triggers = new ActionType[triggerStrings.length];
  115. for (int i = 0; i < triggerStrings.length; i++) {
  116. triggers[i] = ActionManager.getActionType(triggerStrings[i]);
  117. if (triggers[i] == null) {
  118. error("Invalid trigger specified");
  119. return;
  120. } else {
  121. if (i == 0) {
  122. args = triggers[i].getType().getArgTypes();
  123. } else {
  124. if (!triggers[i].getType().equals(triggers[0].getType())) {
  125. error("Triggers are not compatible");
  126. return;
  127. }
  128. }
  129. }
  130. }
  131. } else {
  132. error("No trigger specified");
  133. return;
  134. }
  135. // Read the response
  136. if (properties.containsKey("response")) {
  137. response = properties.getProperty("response").split("\n");
  138. } else {
  139. error("No response specified");
  140. properties.list(System.out);
  141. return;
  142. }
  143. // Read the format change
  144. if (properties.containsKey("format")) {
  145. newFormat = properties.getProperty("format");
  146. }
  147. // Read the conditions
  148. int numConditions = 0;
  149. if (properties.containsKey("conditions")) {
  150. try {
  151. numConditions = Integer.parseInt(properties.getProperty("conditions"));
  152. } catch (NumberFormatException ex) {
  153. error("Invalid number of conditions specified");
  154. return;
  155. }
  156. }
  157. boolean valid = true;
  158. for (int i = 0; i < numConditions; i++) {
  159. valid = valid & readCondition(i);
  160. }
  161. if (valid) {
  162. ActionManager.registerAction(this);
  163. }
  164. }
  165. /** Called to save the action. */
  166. public void save() {
  167. final Properties properties = new Properties();
  168. final StringBuffer triggerString = new StringBuffer();
  169. final StringBuffer responseString = new StringBuffer();
  170. for (ActionType trigger : triggers) {
  171. triggerString.append('|');
  172. triggerString.append(trigger.toString());
  173. }
  174. for (String line : response) {
  175. responseString.append('\n');
  176. responseString.append(line);
  177. }
  178. properties.setProperty("trigger", triggerString.substring(1));
  179. properties.setProperty("conditions", "" + conditions.size());
  180. properties.setProperty("response", responseString.substring(1));
  181. if (newFormat != null) {
  182. properties.setProperty("format", newFormat);
  183. }
  184. int i = 0;
  185. for (ActionCondition condition : conditions) {
  186. properties.setProperty("condition" + i + "-arg", "" + condition.getArg());
  187. properties.setProperty("condition" + i + "-component", condition.getComponent().toString());
  188. properties.setProperty("condition" + i + "-comparison", condition.getComparison().toString());
  189. properties.setProperty("condition" + i + "-target", condition.getTarget());
  190. i++;
  191. }
  192. try {
  193. final FileOutputStream outputStream = new FileOutputStream(file);
  194. properties.store(outputStream, "Created by GUI actions editor");
  195. outputStream.close();
  196. } catch (IOException ex) {
  197. Logger.error(ErrorLevel.ERROR, "Unable to save action: " + group + "/" + name, ex);
  198. }
  199. }
  200. /**
  201. * Reads the specified condition.
  202. * @param condition Condition number to read
  203. * @return True if the condition was read successfully.
  204. */
  205. private boolean readCondition(final int condition) {
  206. // It may help to close your eyes while reading this method.
  207. int arg = -1;
  208. ActionComponent component = null;
  209. ActionComparison comparison = null;
  210. String target = "";
  211. if (properties.containsKey("condition" + condition + "-arg")) {
  212. try {
  213. arg = Integer.parseInt(properties.getProperty("condition" + condition + "-arg"));
  214. } catch (NumberFormatException ex) {
  215. error("Invalid argument number for condition " + condition);
  216. return false;
  217. }
  218. }
  219. if (arg < 0 || arg >= triggers[0].getType().getArity()) {
  220. error("Invalid argument number for condition " + condition);
  221. return false;
  222. }
  223. if (properties.containsKey("condition" + condition + "-component")) {
  224. component = ActionManager.getActionComponent(properties.getProperty("condition" + condition + "-component"));
  225. if (component == null) {
  226. error("Invalid component for condition " + condition);
  227. return false;
  228. }
  229. if (!component.appliesTo().equals(triggers[0].getType().getArgTypes()[arg])) {
  230. error("Component cannot be applied to specified arg in condition " + condition);
  231. return false;
  232. }
  233. } else {
  234. error("No component specified for condition " + condition);
  235. return false;
  236. }
  237. if (properties.containsKey("condition" + condition + "-comparison")) {
  238. comparison = ActionManager.getActionComparison(properties.getProperty("condition" + condition + "-comparison"));
  239. if (comparison == null) {
  240. error("Invalid comparison for condition " + condition);
  241. return false;
  242. }
  243. if (!comparison.appliesTo().equals(component.getType())) {
  244. error("Comparison cannot be applied to specified component in condition " + condition);
  245. return false;
  246. }
  247. } else {
  248. error("No comparison specified for condition " + condition);
  249. return false;
  250. }
  251. if (properties.containsKey("condition" + condition + "-target")) {
  252. target = properties.getProperty("condition" + condition + "-target");
  253. } else {
  254. error("No target specified for condition " + condition);
  255. return false;
  256. }
  257. conditions.add(new ActionCondition(arg, component, comparison, target));
  258. return true;
  259. }
  260. /**
  261. * Raises a trivial error, informing the user of the problem.
  262. * @param message The message to be raised
  263. */
  264. private void error(final String message) {
  265. Logger.error(ErrorLevel.TRIVIAL, "Unable to parse action " + group + "/" + name + ": " + message);
  266. }
  267. /**
  268. * Renames this action to the specified new name.
  269. * @param newName The new name for this action
  270. */
  271. public void rename(final String newName) {
  272. file.renameTo(new File(file.getParent() + System.getProperty("file.separator") + newName));
  273. name = newName;
  274. }
  275. /**
  276. * Sets the group of this action.
  277. * @param newGroup The new group for this action
  278. */
  279. public void setGroup(final String newGroup) {
  280. group = newGroup;
  281. final String fs = System.getProperty("file.separator");
  282. final String location = ActionManager.getDirectory() + group + fs + name;
  283. file.renameTo(new File(location));
  284. }
  285. /**
  286. * Deletes this action.
  287. */
  288. public void delete() {
  289. file.delete();
  290. }
  291. /**
  292. * Retrieves a list of this action's conditions.
  293. * @return A list of this action's conditions
  294. */
  295. public List<ActionCondition> getConditions() {
  296. return conditions;
  297. }
  298. /**
  299. * Sets this action's conditions.
  300. * @param conditions A list of conditions to use
  301. */
  302. public void setConditions(final List<ActionCondition> conditions) {
  303. this.conditions = conditions;
  304. }
  305. /**
  306. * Retrieves this action's triggers.
  307. * @return The triggers used by this action
  308. */
  309. public ActionType[] getTriggers() {
  310. return triggers.clone();
  311. }
  312. /**
  313. * Sets this action's triggers.
  314. * @param triggers The new triggers to use
  315. */
  316. public void setTriggers(final ActionType[] triggers) {
  317. this.triggers = triggers.clone();
  318. ActionManager.unregisterAction(this);
  319. ActionManager.registerAction(this);
  320. }
  321. /**
  322. * Retrieves this action's new format setting.
  323. * @return The format that this action will use, or null if no change
  324. */
  325. public String getNewFormat() {
  326. return newFormat;
  327. }
  328. /**
  329. * Sets this action's new format setting.
  330. * @param newFormat The new 'new format' setting
  331. */
  332. public void setNewFormat(final String newFormat) {
  333. this.newFormat = newFormat;
  334. }
  335. /**
  336. * Retrieves this action's response.
  337. * @return The commands that will be executed if this action is triggered
  338. */
  339. public String[] getResponse() {
  340. return response.clone();
  341. }
  342. /**
  343. * Sets this action's response.
  344. * @param response The new response to use
  345. */
  346. public void setResponse(final String[] response) {
  347. this.response = response.clone();
  348. }
  349. /**
  350. * Retrieves this action's group name.
  351. * @return This action's group name
  352. */
  353. public String getGroup() {
  354. return group;
  355. }
  356. /**
  357. * Retrieves this action's name.
  358. * @return This action's name
  359. */
  360. public String getName() {
  361. return name;
  362. }
  363. /**
  364. * Triggers this action.
  365. * @param format The format of the message that's going to be displayed.
  366. * @param arguments The arguments from the action that caused this trigger.
  367. */
  368. public void trigger(final StringBuffer format, final Object ... arguments) {
  369. for (ActionCondition condition : conditions) {
  370. if (!condition.test(arguments)) {
  371. return;
  372. }
  373. }
  374. InputWindow cw;
  375. CommandParser cp = null;
  376. if (arguments.length > 0 && arguments[0] instanceof FrameContainer) {
  377. cw = ((FrameContainer) arguments[0]).getFrame();
  378. } else if (MainFrame.getMainFrame().getActiveFrame() != null) {
  379. cw = (InputWindow) MainFrame.getMainFrame().getActiveFrame();
  380. } else if (ServerManager.getServerManager().numServers() > 0) {
  381. cw = ServerManager.getServerManager().getServers().get(0).getFrame();
  382. } else {
  383. cw = null;
  384. cp = GlobalCommandParser.getGlobalCommandParser();
  385. }
  386. if (cw != null) {
  387. cp = cw.getCommandParser();
  388. }
  389. for (String command : response) {
  390. cp.parseCommand(cw, ActionManager.substituteVars(command, arguments));
  391. }
  392. if (newFormat != null && format != null) {
  393. format.setLength(0);
  394. format.append(newFormat);
  395. }
  396. }
  397. }