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.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. /*
  2. * Copyright (c) 2006-2010 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.config.prefs.validator.ValidationResponse;
  25. import com.dmdirc.plugins.Plugin;
  26. import com.dmdirc.commandparser.CommandManager;
  27. import com.dmdirc.interfaces.ActionListener;
  28. import com.dmdirc.actions.ActionManager;
  29. import com.dmdirc.actions.CoreActionType;
  30. import com.dmdirc.actions.interfaces.ActionType;
  31. import com.dmdirc.logger.Logger;
  32. import com.dmdirc.logger.ErrorLevel;
  33. import java.io.File;
  34. import java.io.IOException;
  35. import java.io.FileInputStream;
  36. import java.io.FileOutputStream;
  37. import java.util.ArrayList;
  38. import java.util.List;
  39. import java.util.Map;
  40. import java.util.HashMap;
  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. // Make sure our scripts dir exists
  79. final File newDir = new File(scriptDir);
  80. if (!newDir.exists()) { newDir.mkdirs(); }
  81. final File savedVariables = new File(scriptDir+"storedVariables");
  82. if (savedVariables.exists()) {
  83. try {
  84. globalVariables.load(new FileInputStream(savedVariables));
  85. } catch (IOException e) {
  86. Logger.userError(ErrorLevel.LOW, "Error reading savedVariables from '"+savedVariables.getPath()+"': "+e.getMessage(), e);
  87. }
  88. }
  89. }
  90. /**
  91. * Called when this plugin is Unloaded
  92. */
  93. @Override
  94. public void onUnload() {
  95. ActionManager.removeListener(this);
  96. CommandManager.unregisterCommand(command);
  97. final File savedVariables = new File(scriptDir+"storedVariables");
  98. try {
  99. globalVariables.store(new FileOutputStream(savedVariables), "# DMDirc Script Plugin savedVariables");
  100. } catch (IOException e) {
  101. Logger.userError(ErrorLevel.LOW, "Error reading savedVariables to '"+savedVariables.getPath()+"': "+e.getMessage(), e);
  102. }
  103. }
  104. /**
  105. * Register all the action types.
  106. * This will unregister all the actions first.
  107. */
  108. private void registerAll() {
  109. ActionManager.removeListener(this);
  110. for (Map.Entry<String, List<ActionType>> entry : ActionManager.getTypeGroups().entrySet()) {
  111. final List<ActionType> types = entry.getValue();
  112. ActionManager.addListener(this, types.toArray(new ActionType[0]));
  113. }
  114. }
  115. /**
  116. * Process an event of the specified type.
  117. *
  118. * @param type The type of the event to process
  119. * @param format Format of messages that are about to be sent. (May be null)
  120. * @param arguments The arguments for the event
  121. */
  122. @Override
  123. public void processEvent(final ActionType type, final StringBuffer format, final Object... arguments) {
  124. // Plugins may to register/unregister action types, so lets reregister all
  125. // the action types. This
  126. if (type.equals(CoreActionType.PLUGIN_LOADED) || type.equals(CoreActionType.PLUGIN_UNLOADED)) {
  127. registerAll();
  128. }
  129. callFunctionAll("action_"+type.toString().toLowerCase(), arguments);
  130. }
  131. /**
  132. * Get a clone of the scripts map.
  133. *
  134. * @return a clone of the scripts map
  135. */
  136. protected Map<String,ScriptEngineWrapper> getScripts() { return new HashMap<String,ScriptEngineWrapper>(scripts); }
  137. /**
  138. * Get a reference to the scriptFactory.
  139. *
  140. * @return a reference to the scriptFactory
  141. */
  142. protected ScriptEngineManager getScriptFactory() { return scriptFactory; }
  143. /**
  144. * Get a reference to the JavaScriptHelper
  145. *
  146. * @return a reference to the JavaScriptHelper
  147. */
  148. protected JavaScriptHelper getJavaScriptHelper() { return jsHelper; }
  149. /**
  150. * Get a reference to the GlobalVariables Properties
  151. *
  152. * @return a reference to the GlobalVariables Properties
  153. */
  154. protected TypedProperties getGlobalVariables() { return globalVariables; }
  155. /**
  156. * Get the name of the directory where scripts should be stored.
  157. *
  158. * @return The name of the directory where scripts should be stored.
  159. */
  160. protected String getScriptDir() { return scriptDir; }
  161. /** Reload all scripts */
  162. public void rehash() {
  163. for (final ScriptEngineWrapper engine : scripts.values()) {
  164. engine.reload();
  165. }
  166. // Advise the Garbage collector that now would be a good time to run
  167. System.gc();
  168. }
  169. /**
  170. * Call a function in all scripts.
  171. *
  172. * @param functionName Name of function
  173. * @param args Arguments for function
  174. */
  175. private void callFunctionAll(final String functionName, final Object... args) {
  176. for (final ScriptEngineWrapper engine : scripts.values()) {
  177. engine.callFunction(functionName, args);
  178. }
  179. }
  180. /**
  181. * Unload a script file.
  182. *
  183. * @param scriptFilename Path to script
  184. */
  185. public void unloadScript(final String scriptFilename) {
  186. if (scripts.containsKey(scriptFilename)) {
  187. // Tell it that its about to be unloaded.
  188. (scripts.get(scriptFilename)).callFunction("onUnload");
  189. // Remove the script
  190. scripts.remove(scriptFilename);
  191. // Advise the Garbage collector that now would be a good time to run
  192. System.gc();
  193. }
  194. }
  195. /**
  196. * Load a script file into a new jsEngine
  197. *
  198. * @param scriptFilename Path to script
  199. * @return true for Success (or already loaded), false for fail. (Fail occurs if script already exists, or if it has errors)
  200. */
  201. public boolean loadScript(final String scriptFilename) {
  202. if (!scripts.containsKey(scriptFilename)) {
  203. try {
  204. final ScriptEngineWrapper wrapper = new ScriptEngineWrapper(this, scriptFilename);
  205. scripts.put(scriptFilename, wrapper);
  206. } catch (Exception e) {
  207. Logger.userError(ErrorLevel.LOW, "Error loading '"+scriptFilename+"': "+e.getMessage(), e);
  208. return false;
  209. }
  210. }
  211. return true;
  212. }
  213. /**
  214. * Check any further Prerequisites for this plugin to load that can not be
  215. * checked using metainfo.
  216. *
  217. * @return ValidationResponse detailign if the plugin passes any extra checks
  218. * that plugin.info can't handle
  219. */
  220. public ValidationResponse checkPrerequisites() {
  221. if (getScriptFactory().getEngineByName("JavaScript") == null) {
  222. return new ValidationResponse("JavaScript Scripting Engine not found.");
  223. } else {
  224. return new ValidationResponse();
  225. }
  226. }
  227. /**
  228. * Get the reason for checkPrerequisites failing.
  229. *
  230. * @return Human-Readble reason for checkPrerequisites failing.
  231. */
  232. public String checkPrerequisitesReason() {
  233. if (getScriptFactory().getEngineByName("JavaScript") == null) {
  234. return "JavaScript Scripting Engine not found.";
  235. } else {
  236. return "";
  237. }
  238. }
  239. }