d2b39541179a4bb509272828cd2dec64af0c4bf0
[org.ibex.core.git] / src / org / xwt / Trap.java
1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 import org.xwt.util.*;
5 import java.util.*;
6 import org.mozilla.javascript.*;
7
8 /**
9  *  This class encapsulates a single trap placed on a given node. The
10  *  traps for a given property name on a given box are maintained as a
11  *  linked list stack, with the most recently placed trap at the head
12  *  of the list.
13  */
14 public class Trap {
15
16     // Static Data //////////////////////////////////////////////////////////////
17
18     /** a vector of weak references to all instances of Trap; used for retheming */
19     private static Vec allTraps = new Vec(1000);
20
21     /** List of properties that cannot be trapped */
22     private static final Hash PROHIBITED = new Hash(120, 3);
23
24     static {
25         String[] p = new String[] {
26             "sizetoimage", "shrink", "hshrink", "vshrink", "x", "y", "width", "height",
27             "flex", "align", "invisible", "absolute", "globalx", "globaly",
28             "minwidth", "minheight", "height", "width", "maxwidth", "maxheight", 
29             "numchildren", "hpad", "vpad", "doublebuffered", "cursor",
30             "mousex", "mousey", "xwt", "static", "mouseinside", "root", "thisbox", "indexof", "svg"
31         };
32         for(int i=0; i<p.length; i++) PROHIBITED.put(p[i], Boolean.TRUE);
33     };
34
35     // Instance Members ////////////////////////////////////////////////////////
36
37     /** the box on which this trap was placed */
38     private Box trapee = null;
39
40     /** If this trap was actually placed on a root proxy, this is a reference to the proxy */
41     private Scriptable rp = null;
42     
43     /** the function for this trap */
44     Function f = null;
45
46     /** the name of the property that this trap was placed on */
47     private String name = null;
48
49     /** the next trap down the trap stack */
50     private Trap next = null;
51
52     /** true if this is a read-trap */
53     boolean isreadtrap = false;
54
55     /** The nodeName of the Template whose script placed the trap. See Template.nodeName for more detail. */
56     private String placerNodeName = null;
57
58     /** the index of this Trap in the allTraps vector */
59     private int indexInAllTraps = 0;
60
61     // Static Methods //////////////////////////////////////////////////////////////////////////
62
63     /**
64      *  adds a trap.
65      *  @param trapee the box to place the trap on
66      *  @param name the name of the property to trap on
67      *  @param f the function to place as a trap
68      *  @param isreadtrap true iff this is a read (double-underscore) trap
69      *  @param rp if this trap is being placed via a rootproxy, this is that proxy object.
70      */
71     static void addTrap(Box trapee, String name, Function f, boolean isreadtrap, Scriptable rp) {
72
73         if (PROHIBITED.get(name) != null || name.startsWith("xwt_")) {
74             System.out.println("Error: you cannot place traps on special property \"" + name + "\"");
75             return;
76         }
77
78         // find out what script is currently running
79         String placerNodeName = JSObject.getCurrentFunctionSourceName();
80
81         // check if this script has already placed a trap on this property
82         if (trapee.traps == null) trapee.traps = new Hash(10, 3);
83         for(Trap t = (Trap)trapee.traps.get(name); t != null; t = t.next) if (t.placerNodeName.equals(placerNodeName)) return;
84         
85         // actually place the trap
86         Trap t = new Trap();
87         t.next = (Trap)trapee.traps.get(name);
88         trapee.traps.put(name, t);
89         t.trapee = trapee;
90         t.f = f;
91         t.placerNodeName = placerNodeName;
92         t.rp = rp;
93         t.name = name;
94         t.isreadtrap = isreadtrap;
95
96         // make sure that the surface knows when we place traps on these two properties (slightly inelegant)
97         if (trapee.surface != null && (name.equals("KeyPressed") || name.equals("KeyReleased"))) {
98             trapee.surface.keywatchers.removeElement(trapee);
99             trapee.surface.keywatchers.addElement(trapee);
100         }
101     }
102
103     /** returns the function placed as a trap on property <code>name</code> of box <code>b</code> by the currently-running script */
104     public static Trap getTrap(Box b, String name) {
105         if (b.traps == null) return null;
106
107         String currentFunctionNodeName = JSObject.getCurrentFunctionSourceName();
108         for(Trap cur = (Trap)b.traps.get(name); cur != null; cur = cur.next)
109             if (cur.placerNodeName.equals(currentFunctionNodeName))
110                 return cur;
111
112         return null;
113     }
114
115     /** Called by Rhino's arguments.cascade. Note: cx will be null if this was invoked from perform() rather than from a script. */
116     public static final Function cascadeFunction = new CascadeFunction();
117     private static class CascadeFunction extends JSObject implements Function {
118         CascadeFunction() { setSeal(true); }
119         public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; }
120         public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) {
121             Trap currentTrap = TrapContext.get().currentTrap;
122             if (currentTrap == null || (cx != null && Context.getCurrentContext().currentFunction != currentTrap.f)) {
123                 if (Log.on) Log.log(this, "attempt to cascade() by a function that was not invoked as a trap at " +
124                                     cx.interpreterSourceFile + ":" + cx.interpreterLine);
125                 return null;
126             }
127             if (args.length != 0) TrapContext.get().putCascadeHappened = true;
128             Trap t = currentTrap.next;
129             // if we've hit the end of the trap stack, just do a put(,,,true)
130             if (t == null) {
131                 if (args.length == 0) return currentTrap.trapee.get(currentTrap.name, currentTrap.trapee, true);
132                 currentTrap.trapee.put(currentTrap.name, currentTrap.trapee, args[0], true);
133                 return null;
134             }
135             return t.perform(args);
136         }
137     };
138
139     /** called by Rhino's arguments.trapee hack */
140     public static Object currentTrapee() {
141         Trap current = TrapContext.get().currentTrap;
142         if (current == null) return null;
143         else if (current.rp != null) return current.rp;
144         else return current.trapee;
145     }
146
147     /** removes all traps whose function's ultimate parent scope is <tt>b</tt>. Used for retheming */
148     public static void removeAllTrapsByBox(Box b) {
149         for(int i=0; i<allTraps.size(); i++) {
150             Trap t = (Trap)((Weak)allTraps.elementAt(i)).get();
151             if (t == null) continue;
152             for(Scriptable cur = t.f; cur != null; cur = cur.getParentScope()) {
153                 if (cur == b) {
154                     t.delete();
155                     i--;
156                     break;
157                 }
158             }
159         }
160     }
161
162     // Instance Methods //////////////////////////////////////////////////////////////////////////
163
164     private Trap() {
165         indexInAllTraps = allTraps.size();
166         allTraps.addElement(Platform.getWeak(this));
167     }
168
169     /** perform this trap -- arg.length == 0 if this is a get; otherwise it contains a single element to be put */
170     public Object perform(Object[] arg) {
171         TrapContext tc = TrapContext.get();
172
173         // save both thread-locals on the stack and update their values
174         Trap save_currentTrap = tc.currentTrap;
175         tc.currentTrap = this;
176
177         boolean save_putCascadeHappened = tc.putCascadeHappened; 
178         tc.putCascadeHappened = false;
179
180         // invoke the trap function
181         try {
182             if (!isreadtrap && arg.length == 0) return cascadeFunction.call(null, null, null, arg);
183
184             if (f == null) {
185                 if (Log.verbose) Log.log(this, "debug: reclaimed a dangling trap on property " + name);
186                 Object ret = cascadeFunction.call(null, null, null, arg);
187                 delete();
188                 return ret;
189             }
190             
191             Object ret = f.call(Context.enter(), f.getParentScope(), f.getParentScope(), arg);
192             
193             // autocascade if required
194             if (arg.length > 0 && !isreadtrap && !tc.putCascadeHappened) cascadeFunction.call(null, null, null, arg);
195             
196             return ret;
197
198         } catch (EcmaError e) {
199             if (Log.on) Log.log(this, "WARNING: uncaught interpreter exception: " + e.getMessage());
200             if (Log.on) Log.log(this, "         thrown from within trap '" + name + "' at " + e.getSourceName() + ":" + e.getLineNumber());
201         } catch (JavaScriptException e) {
202             if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e.getMessage());
203             if (Log.on) Log.log(this, "         thrown from within trap '" + name + "' at " + e.sourceFile + ":" + e.line);
204         } finally {
205             // restore the thread-locals
206             tc.putCascadeHappened = save_putCascadeHappened;
207             tc.currentTrap = save_currentTrap;
208             tc.trapDepth--;
209         }
210         return null;
211     }
212
213     /** removes this trap */
214     public void delete() {
215         for(Trap last = null, cur = (Trap)trapee.traps.get(name); cur != null; last = cur, cur = cur.next) {
216             if (cur != this) continue;
217             else if (last != null) last.next = cur.next;
218             else if (cur.next == null) trapee.traps.remove(name);
219             else trapee.traps.put(name, cur.next);
220         }
221         if (trapee.surface != null && !trapee.is_trapped("KeyPressed") && !trapee.is_trapped("KeyReleased"))
222             trapee.surface.keywatchers.removeElement(trapee);
223         if (allTraps.size() == 1) allTraps.setSize(0);
224         else {
225             allTraps.setElementAt(allTraps.elementAt(allTraps.size() - 1), indexInAllTraps);
226             allTraps.setSize(allTraps.size() - 1);
227         }
228     }
229
230     /** per-thread storage for Traps */
231     private static class TrapContext {
232
233         private static Hash trapContextByThread = new Hash();
234         private TrapContext() { }
235
236         private boolean putCascadeHappened = false;
237         private Trap currentTrap = null;
238         private int trapDepth = 0;
239
240         /** returns the TrapContext for the current thread */
241         static TrapContext get() {
242             TrapContext ret = (TrapContext)trapContextByThread.get(Thread.currentThread());
243             if (ret == null) {
244                 ret = new TrapContext();
245                 trapContextByThread.put(Thread.currentThread(), ret);
246             }
247             return ret;
248         }
249
250     }
251
252 }