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.

ScriptPlugin.java 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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.addons.scriptplugin;
  23. import com.dmdirc.Main;
  24. import com.dmdirc.actions.ActionManager;
  25. import com.dmdirc.actions.CoreActionType;
  26. import com.dmdirc.actions.interfaces.ActionType;
  27. import com.dmdirc.commandparser.CommandManager;
  28. import com.dmdirc.util.validators.ValidationResponse;
  29. import com.dmdirc.interfaces.ActionListener;
  30. import com.dmdirc.logger.ErrorLevel;
  31. import com.dmdirc.logger.Logger;
  32. import com.dmdirc.plugins.Plugin;
  33. import com.dmdirc.util.StreamUtil;
  34. import java.io.File;
  35. import java.io.FileInputStream;
  36. import java.io.FileOutputStream;
  37. import java.io.IOException;
  38. import java.util.HashMap;
  39. import java.util.List;
  40. import java.util.Map;
  41. import javax.script.ScriptEngineManager;
  42. /**
  43. * This allows javascript scripts to be used in DMDirc.
  44. *
  45. * @author Shane 'Dataforce' McCormack
  46. */
  47. public final class ScriptPlugin extends Plugin implements ActionListener {
  48. /** The ScriptCommand we created */
  49. private ScriptCommand command = null;
  50. /** Script Directory */
  51. private final String scriptDir = Main.getConfigDir() + "scripts/";
  52. /** Script Engine Manager */
  53. private ScriptEngineManager scriptFactory = new ScriptEngineManager();
  54. /** Instance of the javaScriptHelper class */
  55. private JavaScriptHelper jsHelper = new JavaScriptHelper();
  56. /** Store Script State Name,Engine */
  57. private Map<String, ScriptEngineWrapper> scripts = new HashMap<String, ScriptEngineWrapper>();
  58. /** Used to store permanent variables */
  59. protected TypedProperties globalVariables = new TypedProperties();
  60. /**
  61. * Creates a new instance of the Script Plugin.
  62. */
  63. public ScriptPlugin() {
  64. super();
  65. // Add the JS Helper to the scriptFactory
  66. getScriptFactory().put("globalHelper", getJavaScriptHelper());
  67. getScriptFactory().put("globalVariables", getGlobalVariables());
  68. }
  69. /**
  70. * Called when the plugin is loaded.
  71. */
  72. @Override
  73. public void onLoad() {
  74. // Register the plugin_loaded action initially, this will be called
  75. // after this method finishes for us to register the rest.
  76. ActionManager.addListener(this, CoreActionType.PLUGIN_LOADED);
  77. command = new ScriptCommand(this);
  78. CommandManager.registerCommand(command);
  79. // Make sure our scripts dir exists
  80. final File newDir = new File(scriptDir);
  81. if (!newDir.exists()) { newDir.mkdirs(); }
  82. final File savedVariables = new File(scriptDir+"storedVariables");
  83. if (savedVariables.exists()) {
  84. FileInputStream fis = null;
  85. try {
  86. fis = new FileInputStream(savedVariables);
  87. globalVariables.load(fis);
  88. } catch (IOException e) {
  89. Logger.userError(ErrorLevel.LOW, "Error reading savedVariables from '"+savedVariables.getPath()+"': "+e.getMessage(), e);
  90. } finally {
  91. StreamUtil.close(fis);
  92. }
  93. }
  94. }
  95. /**
  96. * Called when this plugin is Unloaded
  97. */
  98. @Override
  99. public void onUnload() {
  100. ActionManager.removeListener(this);
  101. CommandManager.unregisterCommand(command);
  102. final File savedVariables = new File(scriptDir+"storedVariables");
  103. FileOutputStream fos = null;
  104. try {
  105. fos = new FileOutputStream(savedVariables);
  106. globalVariables.store(fos, "# DMDirc Script Plugin savedVariables");
  107. } catch (IOException e) {
  108. Logger.userError(ErrorLevel.LOW, "Error reading savedVariables to '"+savedVariables.getPath()+"': "+e.getMessage(), e);
  109. } finally {
  110. StreamUtil.close(fos);
  111. }
  112. }
  113. /**
  114. * Register all the action types.
  115. * This will unregister all the actions first.
  116. */
  117. private void registerAll() {
  118. ActionManager.removeListener(this);
  119. for (Map.Entry<String, List<ActionType>> entry : ActionManager.getTypeGroups().entrySet()) {
  120. final List<ActionType> types = entry.getValue();
  121. ActionManager.addListener(this, types.toArray(new ActionType[0]));
  122. }
  123. }
  124. /**
  125. * Process an event of the specified type.
  126. *
  127. * @param type The type of the event to process
  128. * @param format Format of messages that are about to be sent. (May be null)
  129. * @param arguments The arguments for the event
  130. */
  131. @Override
  132. public void processEvent(final ActionType type, final StringBuffer format, final Object... arguments) {
  133. // Plugins may to register/unregister action types, so lets reregister all
  134. // the action types. This
  135. if (type.equals(CoreActionType.PLUGIN_LOADED) || type.equals(CoreActionType.PLUGIN_UNLOADED)) {
  136. registerAll();
  137. }
  138. callFunctionAll("action_"+type.toString().toLowerCase(), arguments);
  139. }
  140. /**
  141. * Get a clone of the scripts map.
  142. *
  143. * @return a clone of the scripts map
  144. */
  145. protected Map<String, ScriptEngineWrapper> getScripts() { return new HashMap<String, ScriptEngineWrapper>(scripts); }
  146. /**
  147. * Get a reference to the scriptFactory.
  148. *
  149. * @return a reference to the scriptFactory
  150. */
  151. protected ScriptEngineManager getScriptFactory() { return scriptFactory; }
  152. /**
  153. * Get a reference to the JavaScriptHelper
  154. *
  155. * @return a reference to the JavaScriptHelper
  156. */
  157. protected JavaScriptHelper getJavaScriptHelper() { return jsHelper; }
  158. /**
  159. * Get a reference to the GlobalVariables Properties
  160. *
  161. * @return a reference to the GlobalVariables Properties
  162. */
  163. protected TypedProperties getGlobalVariables() { return globalVariables; }
  164. /**
  165. * Get the name of the directory where scripts should be stored.
  166. *
  167. * @return The name of the directory where scripts should be stored.
  168. */
  169. protected String getScriptDir() { return scriptDir; }
  170. /** Reload all scripts */
  171. public void rehash() {
  172. for (final ScriptEngineWrapper engine : scripts.values()) {
  173. engine.reload();
  174. }
  175. // Advise the Garbage collector that now would be a good time to run
  176. System.gc();
  177. }
  178. /**
  179. * Call a function in all scripts.
  180. *
  181. * @param functionName Name of function
  182. * @param args Arguments for function
  183. */
  184. private void callFunctionAll(final String functionName, final Object... args) {
  185. for (final ScriptEngineWrapper engine : scripts.values()) {
  186. engine.callFunction(functionName, args);
  187. }
  188. }
  189. /**
  190. * Unload a script file.
  191. *
  192. * @param scriptFilename Path to script
  193. */
  194. public void unloadScript(final String scriptFilename) {
  195. if (scripts.containsKey(scriptFilename)) {
  196. // Tell it that its about to be unloaded.
  197. (scripts.get(scriptFilename)).callFunction("onUnload");
  198. // Remove the script
  199. scripts.remove(scriptFilename);
  200. // Advise the Garbage collector that now would be a good time to run
  201. System.gc();
  202. }
  203. }
  204. /**
  205. * Load a script file into a new jsEngine
  206. *
  207. * @param scriptFilename Path to script
  208. * @return true for Success (or already loaded), false for fail. (Fail occurs if script already exists, or if it has errors)
  209. */
  210. public boolean loadScript(final String scriptFilename) {
  211. if (!scripts.containsKey(scriptFilename)) {
  212. try {
  213. final ScriptEngineWrapper wrapper = new ScriptEngineWrapper(this, scriptFilename);
  214. scripts.put(scriptFilename, wrapper);
  215. } catch (Exception e) {
  216. Logger.userError(ErrorLevel.LOW, "Error loading '"+scriptFilename+"': "+e.getMessage(), e);
  217. return false;
  218. }
  219. }
  220. return true;
  221. }
  222. /**
  223. * Check any further Prerequisites for this plugin to load that can not be
  224. * checked using metainfo.
  225. *
  226. * @return ValidationResponse detailign if the plugin passes any extra checks
  227. * that plugin.info can't handle
  228. */
  229. public ValidationResponse checkPrerequisites() {
  230. if (getScriptFactory().getEngineByName("JavaScript") == null) {
  231. return new ValidationResponse("JavaScript Scripting Engine not found.");
  232. } else {
  233. return new ValidationResponse();
  234. }
  235. }
  236. /**
  237. * Get the reason for checkPrerequisites failing.
  238. *
  239. * @return Human-Readble reason for checkPrerequisites failing.
  240. */
  241. public String checkPrerequisitesReason() {
  242. if (getScriptFactory().getEngineByName("JavaScript") == null) {
  243. return "JavaScript Scripting Engine not found.";
  244. } else {
  245. return "";
  246. }
  247. }
  248. }