]> git.pond.sub.org Git - eow/blob - static/dojo-release-1.1.1/dojo/_base/_loader/hostenv_rhino.js
Comment class stub
[eow] / static / dojo-release-1.1.1 / dojo / _base / _loader / hostenv_rhino.js
1 /*
2 * Rhino host environment
3 */
4
5 if(dojo.config["baseUrl"]){
6         dojo.baseUrl = dojo.config["baseUrl"];
7 }else{
8         dojo.baseUrl = "./";
9 }
10
11 dojo.locale = dojo.locale || String(java.util.Locale.getDefault().toString().replace('_','-').toLowerCase());
12 dojo._name = 'rhino';
13 dojo.isRhino = true;
14
15 if(typeof print == "function"){
16         console.debug = print;
17 }
18
19 if(typeof dojo["byId"] == "undefined"){
20         dojo.byId = function(id, doc){
21                 if(id && (typeof id == "string" || id instanceof String)){
22                         if(!doc){ doc = document; }
23                         return doc.getElementById(id);
24                 }
25                 return id; // assume it's a node
26         }
27 }
28
29 // see comments in spidermonkey loadUri
30 dojo._loadUri = function(uri, cb){
31         try{
32                 var local = (new java.io.File(uri)).exists();
33                 if(!local){
34                         try{
35                                 // try it as a file first, URL second
36                                 var stream = (new java.net.URL(uri)).openStream();
37                                 // close the stream so we don't leak resources
38                                 stream.close();
39                         }catch(e){
40                                 // no debug output; this failure just means the uri was not found.
41                                 return false;
42                         }
43                 }
44                 //FIXME: Use Rhino 1.6 native readFile/readUrl if available?
45                 if(cb){
46                         var contents = (local ? readText : readUri)(uri, "UTF-8");
47                         cb(eval('('+contents+')'));
48                 }else{
49                         load(uri);
50                 }
51                 return true;
52         }catch(e){
53                 console.debug("rhino load('" + uri + "') failed. Exception: " + e);
54                 return false;
55         }
56 }
57
58 dojo.exit = function(exitcode){ 
59         quit(exitcode);
60 }
61
62 // Hack to determine current script...
63 //
64 // These initial attempts failed:
65 //   1. get an EcmaError and look at e.getSourceName(): try {eval ("static in return")} catch(e) { ...
66 //   Won't work because NativeGlobal.java only does a put of "name" and "message", not a wrapped reflecting object.
67 //   Even if the EcmaError object had the sourceName set.
68 //  
69 //   2. var e = Packages.org.mozilla.javascript.Context.getCurrentContext().reportError('');
70 //   Won't work because it goes directly to the errorReporter, not the return value.
71 //   We want context.interpreterSourceFile and context.interpreterLine, which are used in static Context.getSourcePositionFromStack
72 //   (set by Interpreter.java at interpretation time, if in interpreter mode).
73 //
74 //   3. var e = Packages.org.mozilla.javascript.Context.getCurrentContext().reportRuntimeError('');
75 //   This returns an object, but e.message still does not have source info.
76 //   In compiler mode, perhaps not set; in interpreter mode, perhaps not used by errorReporter?
77 //
78 // What we found works is to do basically the same hack as is done in getSourcePositionFromStack,
79 // making a new java.lang.Exception() and then calling printStackTrace on a string stream.
80 // We have to parse the string for the .js files (different from the java files).
81 // This only works however in compiled mode (-opt 0 or higher).
82 // In interpreter mode, entire stack is java.
83 // When compiled, printStackTrace is like:
84 // java.lang.Exception
85 //      at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
86 //      at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
87 //      at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
88 //      at java.lang.reflect.Constructor.newInstance(Constructor.java:274)
89 //      at org.mozilla.javascript.NativeJavaClass.constructSpecific(NativeJavaClass.java:228)
90 //      at org.mozilla.javascript.NativeJavaClass.construct(NativeJavaClass.java:185)
91 //      at org.mozilla.javascript.ScriptRuntime.newObject(ScriptRuntime.java:1269)
92 //      at org.mozilla.javascript.gen.c2.call(/Users/mda/Sites/burstproject/testrhino.js:27)
93 //    ...
94 //      at org.mozilla.javascript.tools.shell.Main.main(Main.java:76)
95 //
96 // Note may get different answers based on:
97 //    Context.setOptimizationLevel(-1)
98 //    Context.setGeneratingDebug(true)
99 //    Context.setGeneratingSource(true) 
100 //
101 // Some somewhat helpful posts:
102 //    http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&selm=9v9n0g%246gr1%40ripley.netscape.com
103 //    http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&selm=3BAA2DC4.6010702%40atg.com
104 //
105 // Note that Rhino1.5R5 added source name information in some exceptions.
106 // But this seems not to help in command-line Rhino, because Context.java has an error reporter
107 // so no EvaluationException is thrown.
108
109 // do it by using java java.lang.Exception
110 dojo._rhinoCurrentScriptViaJava = function(depth){
111     var optLevel = Packages.org.mozilla.javascript.Context.getCurrentContext().getOptimizationLevel();  
112     var caw = new java.io.CharArrayWriter();
113     var pw = new java.io.PrintWriter(caw);
114     var exc = new java.lang.Exception();
115     var s = caw.toString();
116     // we have to exclude the ones with or without line numbers because they put double entries in:
117     //   at org.mozilla.javascript.gen.c3._c4(/Users/mda/Sites/burstproject/burst/Runtime.js:56)
118     //   at org.mozilla.javascript.gen.c3.call(/Users/mda/Sites/burstproject/burst/Runtime.js)
119     var matches = s.match(/[^\(]*\.js\)/gi);
120     if(!matches){
121                 throw Error("cannot parse printStackTrace output: " + s);
122         }
123
124     // matches[0] is entire string, matches[1] is this function, matches[2] is caller, ...
125     var fname = ((typeof depth != 'undefined')&&(depth)) ? matches[depth + 1] : matches[matches.length - 1];
126     var fname = matches[3];
127         if(!fname){ fname = matches[1]; }
128     // print("got fname '" + fname + "' from stack string '" + s + "'");
129     if (!fname){ throw Error("could not find js file in printStackTrace output: " + s); }
130     //print("Rhino getCurrentScriptURI returning '" + fname + "' from: " + s); 
131     return fname;
132 }
133
134 // reading a file from disk in Java is a humiliating experience by any measure.
135 // Lets avoid that and just get the freaking text
136 function readText(path, encoding){
137         encoding = encoding || "utf-8";
138         // NOTE: we intentionally avoid handling exceptions, since the caller will
139         // want to know
140         var jf = new java.io.File(path);
141         var is = new java.io.FileInputStream(jf);
142         return dj_readInputStream(is, encoding);
143 }
144
145 function readUri(uri, encoding){
146         var conn = (new java.net.URL(uri)).openConnection();
147         encoding = encoding || conn.getContentEncoding() || "utf-8";
148         var is = conn.getInputStream();
149         return dj_readInputStream(is, encoding);
150 }
151
152 function dj_readInputStream(is, encoding){
153         var input = new java.io.BufferedReader(new java.io.InputStreamReader(is, encoding));
154         try {
155                 var sb = new java.lang.StringBuffer();
156                 var line = "";
157                 while((line = input.readLine()) !== null){
158                         sb.append(line);
159                         sb.append(java.lang.System.getProperty("line.separator"));
160                 }
161                 return sb.toString();
162         } finally {
163                 input.close();
164         }
165 }
166
167 // call this now because later we may not be on the top of the stack
168 if(
169         (!dojo.config.libraryScriptUri)||
170         (!dojo.config.libraryScriptUri.length)
171 ){
172         try{
173                 dojo.config.libraryScriptUri = dojo._rhinoCurrentScriptViaJava(1);
174         }catch(e){
175                 // otherwise just fake it
176                 if(dojo.config["isDebug"]){
177                         print("\n");
178                         print("we have no idea where Dojo is located.");
179                         print("Please try loading rhino in a non-interpreted mode or set a");
180                         print("\n\tdjConfig.libraryScriptUri\n");
181                         print("Setting the dojo path to './'");
182                         print("This is probably wrong!");
183                         print("\n");
184                         print("Dojo will try to load anyway");
185                 }
186                 dojo.config.libraryScriptUri = "./";
187         }
188 }
189
190 // summary:
191 //              return the document object associated with the dojo.global
192 dojo.doc = typeof(document) != "undefined" ? document : null;
193
194 dojo.body = function(){
195         return document.body;   
196 }
197
198 dojo._timeouts = [];
199
200 function clearTimeout(idx){
201         if(!dojo._timeouts[idx]){ return; }
202         dojo._timeouts[idx].stop();
203 }
204
205 function setTimeout(func, delay){
206         // summary: provides timed callbacks using Java threads
207
208         var def={
209                 sleepTime:delay,
210                 hasSlept:false,
211                 
212                 run:function(){
213                         if(!this.hasSlept){
214                                 this.hasSlept=true;
215                                 java.lang.Thread.currentThread().sleep(this.sleepTime);
216                         }
217                         try{
218                                 func();
219                         }catch(e){
220                                 console.debug("Error running setTimeout thread:" + e);
221                         }
222                 }
223         };
224         
225         var runnable = new java.lang.Runnable(def);
226         var thread = new java.lang.Thread(runnable);
227         thread.start();
228         return dojo._timeouts.push(thread)-1;
229 }
230
231 //Register any module paths set up in djConfig. Need to do this
232 //in the hostenvs since hostenv_browser can read djConfig from a
233 //script tag's attribute.
234 if(dojo.config["modulePaths"]){
235         for(var param in dojo.config["modulePaths"]){
236                 dojo.registerModulePath(param, dojo.config["modulePaths"][param]);
237         }
238 }