2002/08/18 05:28:23
[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 Hashtable allTraps = new Hashtable(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     private static Object dummy = new Object();
36
37
38     // Instance Members ////////////////////////////////////////////////////////
39
40     /** the box on which this trap was placed */
41     private Box trapee = null;
42
43     /** If this trap was actually placed on a root proxy, this is a reference to the proxy */
44     private Scriptable rp = null;
45     
46     /** the function for this trap */
47     Function f = null;
48
49     /** the name of the property that this trap was placed on */
50     private String name = null;
51
52     /** the next trap down the trap stack */
53     private Trap next = null;
54
55     /** true if this is a read-trap */
56     boolean isreadtrap = false;
57
58     /** The nodeName of the Template whose script placed the trap. See Template.nodeName for more detail. */
59     private String placerNodeName = null;
60
61     /** our weak reference in the allTraps Hash */
62     private Weak myWeak = Platform.getWeak(this);
63
64
65     // Static Methods //////////////////////////////////////////////////////////////////////////
66
67     /**
68      *  adds a trap.
69      *  @param trapee the box to place the trap on
70      *  @param name the name of the property to trap on
71      *  @param f the function to place as a trap
72      *  @param isreadtrap true iff this is a read (double-underscore) trap
73      *  @param rp if this trap is being placed via a rootproxy, this is that proxy object.
74      */
75     static void addTrap(Box trapee, String name, Function f, boolean isreadtrap, Scriptable rp) {
76
77         if (PROHIBITED.get(name) != null || name.startsWith("xwt_")) {
78             System.out.println("Error: you cannot place traps on special property \"" + name + "\"");
79             return;
80         }
81
82         // find out what script is currently running
83         String placerNodeName = JSObject.getCurrentFunctionSourceName();
84
85         // check if this script has already placed a trap on this property
86         if (trapee.traps == null) trapee.traps = new Hash(10, 3);
87         for(Trap t = (Trap)trapee.traps.get(name); t != null; t = t.next) if (t.placerNodeName.equals(placerNodeName)) return;
88         
89         // actually place the trap
90         Trap t = new Trap();
91         t.next = (Trap)trapee.traps.get(name);
92         trapee.traps.put(name, t);
93         t.trapee = trapee;
94         t.f = f;
95         t.placerNodeName = placerNodeName;
96         t.rp = rp;
97         t.name = name;
98         t.isreadtrap = isreadtrap;
99
100         // make sure that the surface knows when we place traps on these two properties (slightly inelegant)
101         if (trapee.surface != null && (name.equals("KeyPressed") || name.equals("KeyReleased"))) {
102             trapee.surface.keywatchers.removeElement(trapee);
103             trapee.surface.keywatchers.addElement(trapee);
104         }
105     }
106
107     /** returns the function placed as a trap on property <code>name</code> of box <code>b</code> by the currently-running script */
108     public static Trap getTrap(Box b, String name) {
109         if (b.traps == null) return null;
110
111         String currentFunctionNodeName = JSObject.getCurrentFunctionSourceName();
112         for(Trap cur = (Trap)b.traps.get(name); cur != null; cur = cur.next)
113             if (cur.placerNodeName.equals(currentFunctionNodeName))
114                 return cur;
115
116         return null;
117     }
118
119     /** Called by Rhino's arguments.cascade. Note: cx will be null if this was invoked from perform() rather than from a script. */
120     public static final Function cascadeFunction = new CascadeFunction();
121     private static class CascadeFunction extends JSObject implements Function {
122         CascadeFunction() { setSeal(true); }
123         public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; }
124         public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) {
125             Trap currentTrap = TrapContext.get().currentTrap;
126             if (currentTrap == null || (cx != null && Context.getCurrentContext().currentFunction != currentTrap.f)) {
127                 if (Log.on) Log.log(this, "attempt to cascade() by a function that was not invoked as a trap at " +
128                                     cx.interpreterSourceFile + ":" + cx.interpreterLine);
129                 return null;
130             }
131             if (args.length != 0) TrapContext.get().putCascadeHappened = true;
132             Trap t = currentTrap.next;
133             // if we've hit the end of the trap stack, just do a put(,,,true)
134             if (t == null) {
135                 if (args.length == 0) return currentTrap.trapee.get(currentTrap.name, currentTrap.trapee, true);
136                 currentTrap.trapee.put(currentTrap.name, currentTrap.trapee, args[0], true);
137                 return null;
138             }
139             return t.perform(args);
140         }
141     };
142
143     /** called by Rhino's arguments.trapee hack */
144     public static Object currentTrapee() {
145         Trap current = TrapContext.get().currentTrap;
146         if (current == null) return null;
147         else if (current.rp != null) return current.rp;
148         else return current.trapee;
149     }
150
151     /** removes all traps whose function's ultimate parent scope is <tt>b</tt>. Used for retheming */
152     public static void removeAllTrapsByBox(Box b) {
153         Enumeration e = allTraps.keys();
154         while(e.hasMoreElements()) {
155             Weak w = (Weak)e.nextElement();
156             Trap t = (Trap)w.get();
157             if (t == null) {
158                 allTraps.remove(w);
159                 continue;
160             }
161             for(Scriptable cur = t.f; cur != null; cur = cur.getParentScope()) {
162                 if (cur == b) {
163                     t.delete();
164                     break;
165                 }
166             }
167         }
168     }
169
170
171     // Instance Methods //////////////////////////////////////////////////////////////////////////
172
173     private Trap() { allTraps.put(myWeak, dummy); }
174
175     /** perform this trap -- arg.length == 0 if this is a get; otherwise it contains a single element to be put */
176     public Object perform(Object[] arg) {
177         TrapContext tc = TrapContext.get();
178
179         // save both thread-locals on the stack and update their values
180         Trap save_currentTrap = tc.currentTrap;
181         tc.currentTrap = this;
182
183         boolean save_putCascadeHappened = tc.putCascadeHappened; 
184         tc.putCascadeHappened = false;
185
186         // invoke the trap function
187         try {
188             if (!isreadtrap && arg.length == 0) return cascadeFunction.call(null, null, null, arg);
189
190             if (f == null) {
191                 if (Log.verbose) Log.log(this, "debug: reclaimed a dangling trap on property " + name);
192                 Object ret = cascadeFunction.call(null, null, null, arg);
193                 delete();
194                 return ret;
195             }
196             
197             Object ret = f.call(Context.enter(), f.getParentScope(), f.getParentScope(), arg);
198             
199             // autocascade if required
200             if (arg.length > 0 && !isreadtrap && !tc.putCascadeHappened) cascadeFunction.call(null, null, null, arg);
201             
202             return ret;
203
204         } catch (EcmaError e) {
205             if (Log.on) Log.log(this, "WARNING: uncaught interpreter exception: " + e.getMessage());
206             if (Log.on) Log.log(this, "         thrown from within trap '" + name + "' at " + e.getSourceName() + ":" + e.getLineNumber());
207         } catch (JavaScriptException e) {
208             if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e.getMessage());
209             if (Log.on) Log.log(this, "         thrown from within trap '" + name + "' at " + e.sourceFile + ":" + e.line);
210         } finally {
211             // restore the thread-locals
212             tc.putCascadeHappened = save_putCascadeHappened;
213             tc.currentTrap = save_currentTrap;
214             tc.trapDepth--;
215         }
216         return null;
217     }
218
219     /** removes this trap */
220     public void delete() {
221         for(Trap last = null, cur = (Trap)trapee.traps.get(name); cur != null; last = cur, cur = cur.next) {
222             if (cur != this) continue;
223             else if (last != null) last.next = cur.next;
224             else if (cur.next == null) trapee.traps.remove(name);
225             else trapee.traps.put(name, cur.next);
226         }
227         if (trapee.surface != null && !trapee.is_trapped("KeyPressed") && !trapee.is_trapped("KeyReleased"))
228             trapee.surface.keywatchers.removeElement(trapee);
229         allTraps.remove(myWeak);
230     }
231
232     /** per-thread storage for Traps */
233     private static class TrapContext {
234
235         private static Hash trapContextByThread = new Hash();
236         private TrapContext() { }
237
238         private boolean putCascadeHappened = false;
239         private Trap currentTrap = null;
240         private int trapDepth = 0;
241
242         /** returns the TrapContext for the current thread */
243         static TrapContext get() {
244             TrapContext ret = (TrapContext)trapContextByThread.get(Thread.currentThread());
245             if (ret == null) {
246                 ret = new TrapContext();
247                 trapContextByThread.put(Thread.currentThread(), ret);
248             }
249             return ret;
250         }
251
252     }
253
254 }
255