2002/05/16 04:15:12
[org.ibex.core.git] / src / org / xwt / util / JSObject.java
1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt.util;
3
4 import org.mozilla.javascript.*;
5 import java.net.*;
6 import java.io.*;
7 import java.util.*;
8 import org.xwt.*;
9
10 /** Simple implementation of a JavaScript host object.
11  *
12  *  If privateVars is set, then any "var" declaration issued on this
13  *  scope will create a variable visible only to scripts from the same
14  *  directory (package) as the script that made the declaration.
15  *
16  *  This is implemented by making JSObject.Top the ultimate
17  *  parentScope of all privateVars-style JSObjects. Puts to JSObjects
18  *  which are var-decls will not climb the scope chain, and will be
19  *  put directly to the JSObject. Puts which are <i>not</i> var-decls
20  *  will climb the scope chain and will be put to Top, which will then
21  *  re-put the value to the JSObject as a global.
22  */
23 public class JSObject implements Scriptable {
24
25     // Static Data ///////////////////////////////////////////////////////////////////////    
26
27     /** helper; retrieves the 'source code filename' (usually the nodeName) of the currently-executing function in this thread */
28     public static String getCurrentFunctionSourceName() {
29         Context cx = Context.getCurrentContext();
30         if (cx == null) {
31             if (Log.on) Log.log(JSObject.class, "Context.getCurrentContext() is null in getCurrentFunctionSourceName()");
32             return "unknown";
33         }
34         Function cf = cx.currentFunction;
35         if (cf == null) return null;
36         return (cf instanceof InterpretedFunction) ?
37             ((InterpretedFunction)cf).getSourceName() : ((InterpretedScript)cf).getSourceName();
38     }
39
40     /** cache for nodeNameToPackageName(); prevents creation of zillions of String objects */
41     private static Hash nodeNameToPackageNameHash = new Hash(1000, 2);
42
43     /** converts a nodeName (source code filename) into the 'package name' (resource name of its directory) */
44     private static String nodeNameToPackageName(String nodeName) {
45         if (nodeName == null) return null;
46         String ret = (String)nodeNameToPackageNameHash.get(nodeName);
47         if (ret != null) return ret;
48         ret = nodeName;
49         for(int i=0; i<ret.length() - 1; i++)
50             if (ret.charAt(i) == '.' && (ret.charAt(i + 1) == '_' || Character.isDigit(ret.charAt(i + 1)))) {
51                 ret = ret.substring(0, i);
52                 break;
53             }
54         if (ret.lastIndexOf('.') != -1)
55             ret = ret.substring(0, ret.lastIndexOf('.'));
56         ret = ret.intern();
57         nodeNameToPackageNameHash.put(nodeName, ret);
58         return ret;
59     }
60     
61     /** this holds a scope which has been initialized with the standard ECMA objects */
62     public static Scriptable defaultObjects = Context.enter().initStandardObjects(null);
63
64     // Instance Data ///////////////////////////////////////////////////////////////////////    
65
66     /** The properties that holds our scope */
67     protected Hash properties = null;
68     
69     /** If true, put()s and delete()s are prohibited */
70     boolean sealed = false;
71
72     /** If true, variables declared with 'var' become visible only to scripts from the same
73      *  directory/package as the one which created the variable
74      */
75     boolean privateVars = false;
76
77     public JSObject() { }
78     public JSObject(boolean privateVars) { this.privateVars = privateVars; }
79
80     public Object get(String name, Scriptable start) {
81         if (name == null || name.equals("") || properties == null) return null;
82
83         Object ret = properties.get(name, nodeNameToPackageName(getCurrentFunctionSourceName()));
84         if (ret == NOT_FOUND) return null;
85         if (ret != null) return ret;
86         return properties.get(name, null);
87     }
88
89     /** returns the package-private variable <tt>name</tt> associated with <tt>nodeName</tt> */
90     public Object getPrivately(String name, String nodeName) {
91         return properties == null ? null : properties.get(name, nodeNameToPackageName(nodeName));
92     }
93
94     /** puts a property as a private variable, accessible only to scripts in the source code file <tt>nodeName</tt> */
95     public void putPrivately(String name, Object value, String nodeName) {
96         if (!privateVars) {
97             putGlobally(name, null, value);
98             return;
99         }
100         if (properties == null) properties = new Hash();
101
102         // we use NOT_FOUND to mark a variable which exists as a script-local, yet has a value of null
103         if (value == null) value = NOT_FOUND;
104         properties.put(name, nodeNameToPackageName(nodeName), value);
105     }
106
107     /** forces a property to be put globally -- accessible to all scripts */
108     public void putGlobally(String name, Scriptable start, Object value) {
109         if (name == null || name.equals("")) return;
110         if (properties == null) properties = new Hash();
111         properties.put(name, null, value);
112     }
113
114     /**
115      *  if a put is made directly to us (rather than cascading up to
116      *  Top), by a script for whom we are in the ultimate parent
117      *  scope, it must be a var-declaration
118      */
119     public void put(String name, Scriptable start, Object value) {
120         if (sealed) return;
121         if (name == null || name.equals("")) return;
122         for(Scriptable cur = Context.enter().currentFunction; cur != null; cur = cur.getParentScope())
123             if (cur == this) {
124                 putPrivately(name, value, getCurrentFunctionSourceName());
125                 return;
126             }
127         putGlobally(name, start, value);
128     }
129     
130     /** if privateVars is enabled, we always return false, to see if the put propagates up to Top */
131     public boolean has(String name, Scriptable start) {
132         if (!privateVars) return properties != null && properties.get(name) != null;
133         Top.lastByThread.put(Thread.currentThread(), this);
134         return false;
135     }
136     
137     public Object[] getIds() {
138         if (properties == null) return new Object[] { };
139         else return properties.keys();
140     }
141     
142     /** Parent scope of all JSObjects; we use the has(String) method on this object to determine if a put represents a var-declaration or a plain 'ol put */
143     private static class Top implements Scriptable {
144         
145         /** Last JSObject to perform a has(), keyed by thread.
146          *  Assumes that every Top.has() is immediately preceded by a JSObject.has() in the same thread
147          */
148         public static Hash lastByThread = new Hash();
149         
150         public static Top singleton = new Top();
151         private Top() { }
152         
153         public boolean has(String name, Scriptable start) { return true; }
154         public void put(String name, Scriptable start, Object value) {
155             JSObject last = (JSObject)lastByThread.get(Thread.currentThread());
156             if (last.properties != null && last.properties.get(name, nodeNameToPackageName(getCurrentFunctionSourceName())) != null)
157                 last.put(name, start, value);
158             else last.putGlobally(name, start, value);
159         }
160
161         public Object get(String name, Scriptable start) {
162
163             // hack since Rhino needs to be able to grab these functions to create new objects
164             if (name.equals("Object")) return JSObject.defaultObjects.get("Object", null);
165             if (name.equals("Array")) return JSObject.defaultObjects.get("Array", null);
166             if (name.equals("Function")) return JSObject.defaultObjects.get("Function", null);
167             if (name.equals("TypeError")) return JSObject.defaultObjects.get("TypeError", null);
168             if (name.equals("ConversionError")) return JSObject.defaultObjects.get("ConversionError", null);
169             return ((JSObject)lastByThread.get(Thread.currentThread())).get(name, start);
170         }
171
172         // Trivial methods
173         public String getClassName() { return "Top"; }
174         public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; }
175         public void delete(String name) { }
176         public Scriptable getParentScope() { return null; }
177         public void setParentScope(Scriptable p) { }
178         public boolean hasInstance(Scriptable value) { return false; }
179         public Scriptable getPrototype() { return null; }
180         public void setPrototype(Scriptable p) { }
181         public void delete(int i) { }
182         public Object getDefaultValue(Class hint) { return "Top"; }
183         public void put(int i, Scriptable start, Object value) { put(String.valueOf(i), start, value); }
184         public Object get(int i, Scriptable start) { return get(String.valueOf(i), start); }
185         public boolean has(int i, Scriptable start) { return has(String.valueOf(i), start); }
186         public Object[] getIds() { return new Object[] { }; }
187
188     }
189
190
191     // Trivial Methods ///////////////////////////////////////////////////////////
192
193     public void setSeal(boolean doseal) { sealed = doseal; }
194     public void flush() { if (properties != null) properties.clear(); }
195     public void delete(String name) { if (Log.on) Log.log(this, "JSObject.delete() should not be reachable"); }
196     public void delete(int i) { if (Log.on) Log.log(this, "JSObject.delete() should not be reachable"); }
197     public Scriptable getParentScope() { return privateVars ? Top.singleton : null; }
198     public void setParentScope(Scriptable p) { }
199     public boolean hasInstance(Scriptable value) { return false; }
200     public Scriptable getPrototype() { return null; }
201     public void setPrototype(Scriptable p) { }
202     public String getClassName() { return this.getClass().getName(); }
203     public Object getDefaultValue(Class hint) { return toString(); }
204     public void put(int i, Scriptable start, Object value) { put(String.valueOf(i), start, value); }
205     public Object get(int i, Scriptable start) { return get(String.valueOf(i), start); }
206     public boolean has(int i, Scriptable start) { return has(String.valueOf(i), start); }
207
208 }
209