KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > rero > client > script > ScriptManager


1 package rero.client.script;
2
3 import rero.client.DataStructures;
4 import rero.client.Feature;
5 import rero.config.ClientDefaults;
6 import rero.config.ClientState;
7 import rero.config.ClientStateListener;
8 import rero.config.StringList;
9 import rero.util.ClientUtils;
10 import sleep.error.RuntimeWarningWatcher;
11 import sleep.error.ScriptWarning;
12 import sleep.error.SyntaxError;
13 import sleep.error.YourCodeSucksException;
14 import sleep.runtime.ScriptInstance;
15 import sleep.runtime.ScriptLoader;
16
17 import java.io.File JavaDoc;
18 import java.io.IOException JavaDoc;
19 import java.util.*;
20 import java.util.regex.Matcher JavaDoc;
21 import java.util.regex.Pattern JavaDoc;
22 import java.nio.charset.Charset JavaDoc;
23
24 public class ScriptManager extends Feature implements ClientStateListener, RuntimeWarningWatcher
25 {
26     protected ScriptLoader loader;
27     protected Hashtable environment; // shared environment...
28
protected boolean lock = false;
29
30     private static boolean SILENT = false; // for /reload mainly...
31

32     public void init()
33     {
34         loader = (ScriptLoader) getCapabilities().getDataStructure(DataStructures.ScriptLoader);
35         environment = (Hashtable) getCapabilities().getDataStructure(DataStructures.SharedEnv);
36
37         ClientState.getClientState().addClientStateListener("script.files", this);
38     }
39
40     public void storeDataStructures(WeakHashMap data)
41     {
42         data.put(DataStructures.ScriptManager, this);
43     }
44
45     public void hashScripts()
46     {
47         if (lock)
48             return;
49
50         Set unload, load, configured;
51
52         configured = new LinkedHashSet();
53         configured.addAll(ClientState.getClientState().getStringList("script.files").getList());
54
55         load = loader.getScriptsToLoad(configured);
56         unload = loader.getScriptsToUnload(configured);
57
58         load.remove("menus");
59         load.remove("default");
60         load.remove("lame");
61
62         unload.remove("menus");
63         unload.remove("lame");
64         unload.remove("default");
65
66         Iterator i = unload.iterator();
67         while (i.hasNext()) {
68             String JavaDoc tt = (String JavaDoc) i.next();
69             loader.unloadScript(tt);
70
71             if (ClientState.getClientState().isOption("script.verboseLoad", ClientDefaults.script_verboseLoad)) {
72                 getCapabilities().getUserInterface().printStatus("Successfully unloaded script " + tt);
73             }
74         }
75
76         i = load.iterator();
77         while (i.hasNext()) {
78             String JavaDoc tt = (String JavaDoc) i.next();
79             if (!loader.isLoaded(tt)) {
80                 internalScriptLoad(tt); // this check is overly redundant, however if a script loads a script while this operation is
81
// taking place things will have the potential to break, never any fun
82
}
83         }
84     }
85
86     public void loadTheme(String JavaDoc filename)
87     {
88         filename = ClientUtils.getFile(filename).getAbsolutePath();
89
90         if ((new File JavaDoc(filename)).exists()) {
91             internalScriptLoad(filename);
92             loader.unloadScript(filename);
93         } else {
94             getCapabilities().getUserInterface().printStatus("Error loading script: " + new File JavaDoc(filename).getAbsolutePath() + " does not exist");
95         }
96     }
97
98     public void addScript(String JavaDoc filename)
99     {
100         filename = ClientUtils.getFile(filename).getAbsolutePath();
101
102         if ((new File JavaDoc(filename)).exists()) {
103             StringList temp = ClientState.getClientState().getStringList("script.files");
104             String JavaDoc fn = ClientUtils.getFile(filename).getAbsolutePath();
105
106             if (!temp.getList().contains(fn)) {
107                 temp.add(fn);
108                 temp.save();
109                 ClientState.getClientState().sync();
110             } else {
111                 getCapabilities().getUserInterface().printStatus("Script file " + fn + " is already loaded. Grabbing a beer instead");
112             }
113         } else {
114             getCapabilities().getUserInterface().printStatus("Error loading script: " + new File JavaDoc(filename).getAbsolutePath() + " does not exist");
115         }
116     }
117
118     public void evalScript(String JavaDoc code)
119     {
120         try {
121             getCapabilities().getUserInterface().printActive(((ScriptInstance) loader.getScripts().getFirst()).getScriptEnvironment().evaluateExpression(code).toString());
122         }
123         catch (YourCodeSucksException ex) {
124             formatCodeException("/eval input", ex);
125         }
126     }
127
128     public void setDebug(String JavaDoc filename, String JavaDoc debuglevel)
129     {
130         Iterator i = findScripts(filename, ClientState.getClientState().getStringList("script.files").getList()).iterator();
131         while (i.hasNext()) {
132             String JavaDoc scriptf = (String JavaDoc) i.next();
133             setDebugReal(scriptf, debuglevel);
134         }
135     }
136
137     private void setDebugReal(String JavaDoc filename, String JavaDoc debuglevel)
138     {
139         ScriptInstance script = (ScriptInstance)loader.getScriptsByKey().get(filename);
140
141         if (script == null)
142         {
143            getCapabilities().getUserInterface().printStatus("Could not find script " + filename + " to set debug level");
144            return;
145         }
146
147         int debug = script.getDebugFlags();
148
149         if (debuglevel.indexOf("+trace") > -1)
150         {
151            debug = debug | ScriptInstance.DEBUG_TRACE_CALLS;
152         }
153      
154         if (debuglevel.indexOf("-trace") > -1)
155         {
156            debug = debug & ~ScriptInstance.DEBUG_TRACE_CALLS;
157         }
158
159         if (debuglevel.indexOf("-warn") > -1)
160         {
161            debug = debug & ~ScriptInstance.DEBUG_SHOW_WARNINGS;
162         }
163
164         if (debuglevel.indexOf("+warn") > -1)
165         {
166            debug = debug | ScriptInstance.DEBUG_SHOW_WARNINGS;
167         }
168
169         if (debuglevel.indexOf("+all") > -1)
170         {
171            debug = debug | ScriptInstance.DEBUG_SHOW_WARNINGS | ScriptInstance.DEBUG_TRACE_CALLS;
172         }
173
174         if (debuglevel.indexOf("-all") > -1)
175         {
176            debug = debug & ~ScriptInstance.DEBUG_SHOW_WARNINGS & ~ScriptInstance.DEBUG_TRACE_CALLS;
177         }
178
179         script.setDebugFlags(debug);
180
181         getCapabilities().getUserInterface().printStatus("*** Updated debug flags for " + filename);
182     }
183
184     public String JavaDoc evalString(String JavaDoc code)
185     {
186         try {
187             return ((ScriptInstance) loader.getScripts().getFirst()).getScriptEnvironment().evaluateExpression(code).toString();
188         }
189         catch (YourCodeSucksException ex) {
190             formatCodeException("/eval input", ex);
191         }
192         return code;
193     }
194
195     public void reloadScript(String JavaDoc filename)
196     {
197         boolean flag = true;
198
199         Iterator i =
200             findScripts(filename, ClientState.getClientState().getStringList("script.files").getList()).iterator();
201         while (i.hasNext()) {
202             flag = false;
203
204             String JavaDoc scriptf = (String JavaDoc) i.next();
205
206 // if (ClientState.getClientState().isOption("script.verboseLoad", ClientDefaults.script_verboseLoad))
207
// {
208
// getCapabilities().getUserInterface().printStatus("Attempting to reload script " + scriptf);
209
// }
210

211             removeScript(scriptf);
212             addScript(scriptf);
213 // loader.unloadScript(scriptf);
214
// internalScriptLoad(scriptf);
215
}
216
217         if (flag)
218             getCapabilities().getUserInterface().printStatus("Error (re)loading script: " + filename + " isn't loaded");
219     }
220
221     private LinkedList findScripts(String JavaDoc filename, LinkedList theList)
222     {
223         LinkedList goodBye = new LinkedList();
224
225         Iterator i = theList.iterator();
226         while (i.hasNext()) {
227             File JavaDoc temp = new File JavaDoc((String JavaDoc) i.next());
228             if (temp.getName().equals(filename) || temp.getAbsolutePath().equals(filename)) {
229                 goodBye.add(temp.getAbsolutePath());
230             }
231         }
232
233         return goodBye;
234     }
235
236     public void removeScript(String JavaDoc filename)
237     {
238         StringList temp = ClientState.getClientState().getStringList("script.files");
239         Iterator i = findScripts(filename, temp.getList()).iterator();
240
241         while (i.hasNext()) {
242             String JavaDoc remMe = (String JavaDoc) i.next();
243             temp.remove(remMe);
244         }
245
246         temp.save();
247         ClientState.getClientState().sync(); // this will cause all the script values to be rehashed...
248
}
249
250     private static boolean lame = true;
251
252     public void loadLameScripts()
253     {
254         try {
255             if (lame) {
256                 ScriptInstance defaults =
257                     loader.loadScript("lame", ClientState.getClientState().getResourceAsStream("lame.irc"), environment);
258
259                 defaults.addWarningWatcher(this);
260                 defaults.runScript();
261
262                 lame = false;
263             }
264         }
265         catch (Exception JavaDoc ex) {
266
267         }
268     }
269
270     public void loadScripts()
271     {
272         //
273
// do other fun stuff... i.e. script loading and such
274
//
275

276         try {
277             if (ClientState.getClientState().isOption("load.default", true)) {
278                 long start = System.currentTimeMillis();
279                 ScriptInstance defaults =
280                     loader.loadScript("default", ClientState.getClientState().getResourceAsStream("default.irc"), environment);
281 // System.out.println("Default script loaded in: " + (System.currentTimeMillis() - start));
282

283                 defaults.addWarningWatcher(this);
284                 defaults.runScript();
285             }
286
287             if (ClientState.getClientState().isOption("load.menus", true)) {
288                 long start = System.currentTimeMillis();
289                 ScriptInstance defaults =
290                     loader.loadScript("menus", ClientState.getClientState().getResourceAsStream("menus.irc"), environment);
291 // System.out.println("Menu script loaded in: " + (System.currentTimeMillis() - start));
292

293                 defaults.addWarningWatcher(this);
294                 defaults.runScript();
295             }
296
297             if (ClientState.getClientState().isOption("load.lame", false)) {
298                 loadLameScripts();
299             }
300         }
301         catch (YourCodeSucksException ex) {
302             formatCodeException("<Internal Scripts>", ex);
303         }
304         catch (IOException JavaDoc ex) {
305             ex.printStackTrace();
306         }
307
308         Iterator i = ClientState.getClientState().getStringList("script.files").getList().iterator();
309         while (i.hasNext()) {
310             internalScriptLoad((String JavaDoc) i.next());
311         }
312     }
313
314     public void propertyChanged(String JavaDoc name, String JavaDoc value)
315     {
316         hashScripts();
317     }
318
319     private void internalScriptLoad(String JavaDoc scriptFile)
320     {
321         try {
322             String JavaDoc charset = guessCharsetFromFileName(scriptFile);
323
324             // keep old conversion mode
325
boolean charsetConversions = loader.isCharsetConversions();
326             String JavaDoc oldcharset = loader.getCharset();
327
328             // set charset to use when loading script
329
if (charset != null) {
330                 loader.setCharsetConversion(true);
331                 loader.setCharset(charset);
332             }
333
334             ScriptInstance scripti = loader.loadScript(scriptFile, environment);
335
336             // restore previous mode
337
if (charset != null) {
338                 loader.setCharsetConversion(charsetConversions);
339                 loader.setCharset(oldcharset);
340             }
341
342             scripti.addWarningWatcher(this);
343
344             if (ClientState.getClientState().isOption("script.verboseLoad", ClientDefaults.script_verboseLoad)) {
345                 getCapabilities().getUserInterface().printStatus("Successfully loaded script " + new File JavaDoc(scriptFile).getName());
346             }
347
348             scripti.runScript();
349         }
350         catch (YourCodeSucksException ex) {
351             formatCodeException(scriptFile, ex);
352
353             lock = true;
354             removeScript(scriptFile);
355             lock = false;
356         }
357         catch (IOException JavaDoc ex2) {
358             getCapabilities().getUserInterface().printStatus("Error loading " + (new File JavaDoc(scriptFile)).getName() + ": " + ex2.getMessage());
359         }
360         catch (Exception JavaDoc ex3) {
361             getCapabilities().getUserInterface().printStatus("Error loading " + (new File JavaDoc(scriptFile)).getName() + ": " + ex3.getMessage() + " <-- could be a sleep bug, please report :)");
362             ex3.printStackTrace();
363         }
364     }
365
366     private static final Pattern JavaDoc ENCODING_IN_FILE = Pattern.compile(".*\\.(.*?)\\..*$");
367     private static final Pattern JavaDoc ENCODING_IN_EXTENSION = Pattern.compile(".*\\.(.*)$");
368     private static SortedMap charsets = null;
369
370     /**
371      * Script file name may contain charset, like file.charset.irc, or just file.charset
372      *
373      * @param scriptFile file name
374      * @return valid charset if found in file name, null otherwise
375      */

376     private String JavaDoc guessCharsetFromFileName(String JavaDoc scriptFile)
377     {
378         File JavaDoc f = new File JavaDoc(scriptFile);
379         String JavaDoc name = f.getName();
380
381         Matcher JavaDoc mname = ENCODING_IN_FILE.matcher(name);
382         Matcher JavaDoc mext = ENCODING_IN_EXTENSION.matcher(name);
383
384         if (mname.matches()) {
385             // lazy init
386
if (charsets == null) charsets = Charset.availableCharsets();
387             String JavaDoc charset = mname.group(1);
388             if (charsets.containsKey(charset))
389                 return charset;
390         }
391         if (mext.matches()) {
392             String JavaDoc charset = mext.group(1);
393             // skip for .irc files
394
if(charset.equalsIgnoreCase("irc")) return null;
395             // lazy init
396
if (charsets == null) charsets = Charset.availableCharsets();
397             if (charsets.containsKey(charset))
398                 return charset;
399         }
400
401         return null;
402     }
403
404     public void processScriptWarning(ScriptWarning warn)
405     {
406         if (! ClientState.getClientState().isOption("script.ignoreWarnings", ClientDefaults.script_ignoreWarnings)) {
407             String JavaDoc[] temp = warn.getMessage().split("\n");
408
409
410             String JavaDoc fname = warn.getNameShort();
411
412             if (warn.isDebugTrace())
413             {
414                getCapabilities().getUserInterface().printStatus(fname + ":" + warn.getLineNumber() + " " + temp[0]);
415             }
416             else
417             {
418                getCapabilities().getUserInterface().printStatus("*** Script Warning: " + temp[0] + " at " + fname + ":" + warn.getLineNumber());
419             }
420
421             for (int x = 1; x < temp.length; x++) {
422                 getCapabilities().getUserInterface().printStatus(" " + temp[x]);
423             }
424         }
425     }
426
427     private void formatCodeException(String JavaDoc scriptFile, YourCodeSucksException ex)
428     {
429         getCapabilities().getUserInterface().printStatus("*** " + ex.getErrors().size() + " error(s) loading " + scriptFile);
430
431         Iterator i = ex.getErrors().iterator();
432         while (i.hasNext()) {
433             SyntaxError anError = (SyntaxError) i.next();
434             getCapabilities().getUserInterface().printStatus("Error: " + anError.getDescription() + " at line " + anError.getLineNumber());
435             getCapabilities().getUserInterface().printStatus(" " + anError.getCodeSnippet());
436
437             if (anError.getMarker() != null)
438                 getCapabilities().getUserInterface().printStatus(" " + anError.getMarker());
439         }
440     }
441 }
442
443
Popular Tags