2 * Rhino host environment
5 if(dojo.config["baseUrl"]){
6 dojo.baseUrl = dojo.config["baseUrl"];
11 dojo.locale = dojo.locale || String(java.util.Locale.getDefault().toString().replace('_','-').toLowerCase());
15 if(typeof print == "function"){
16 console.debug = print;
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);
25 return id; // assume it's a node
29 // see comments in spidermonkey loadUri
30 dojo._loadUri = function(uri, cb){
32 var local = (new java.io.File(uri)).exists();
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
40 // no debug output; this failure just means the uri was not found.
44 //FIXME: Use Rhino 1.6 native readFile/readUrl if available?
46 var contents = (local ? readText : readUri)(uri, "UTF-8");
47 cb(eval('('+contents+')'));
53 console.debug("rhino load('" + uri + "') failed. Exception: " + e);
58 dojo.exit = function(exitcode){
62 // Hack to determine current script...
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.
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).
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?
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)
94 // at org.mozilla.javascript.tools.shell.Main.main(Main.java:76)
96 // Note may get different answers based on:
97 // Context.setOptimizationLevel(-1)
98 // Context.setGeneratingDebug(true)
99 // Context.setGeneratingSource(true)
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
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.
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);
121 throw Error("cannot parse printStackTrace output: " + s);
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);
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
140 var jf = new java.io.File(path);
141 var is = new java.io.FileInputStream(jf);
142 return dj_readInputStream(is, encoding);
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);
152 function dj_readInputStream(is, encoding){
153 var input = new java.io.BufferedReader(new java.io.InputStreamReader(is, encoding));
155 var sb = new java.lang.StringBuffer();
157 while((line = input.readLine()) !== null){
159 sb.append(java.lang.System.getProperty("line.separator"));
161 return sb.toString();
167 // call this now because later we may not be on the top of the stack
169 (!dojo.config.libraryScriptUri)||
170 (!dojo.config.libraryScriptUri.length)
173 dojo.config.libraryScriptUri = dojo._rhinoCurrentScriptViaJava(1);
175 // otherwise just fake it
176 if(dojo.config["isDebug"]){
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!");
184 print("Dojo will try to load anyway");
186 dojo.config.libraryScriptUri = "./";
191 // return the document object associated with the dojo.global
192 dojo.doc = typeof(document) != "undefined" ? document : null;
194 dojo.body = function(){
195 return document.body;
200 function clearTimeout(idx){
201 if(!dojo._timeouts[idx]){ return; }
202 dojo._timeouts[idx].stop();
205 function setTimeout(func, delay){
206 // summary: provides timed callbacks using Java threads
215 java.lang.Thread.currentThread().sleep(this.sleepTime);
220 console.debug("Error running setTimeout thread:" + e);
225 var runnable = new java.lang.Runnable(def);
226 var thread = new java.lang.Thread(runnable);
228 return dojo._timeouts.push(thread)-1;
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]);