770ad51b35d1d6d032d3034db72fd11138d744ad
[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 java.util.*;
5 import org.xwt.js.*;
6 import org.xwt.util.*;
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 JS rp = null;
45     
46     /** the function for this trap */
47     JS.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, JS.Function f, boolean isreadtrap, JS rp) {
76
77         if (PROHIBITED.get(name) != null || name.startsWith("xwt_")) {
78             Log.log(Trap.class, "Error: you cannot place traps on special property \"" + name + "\"");
79             return;
80         }
81
82         // find out what script is currently running
83         String placerNodeName = JS.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 = JS.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 CascadeFunction cascadeFunction = new CascadeFunction();
121     private static class CascadeFunction extends JS.Function {
122         CascadeFunction() { setSeal(true); }
123         public Object _call(JS.Array args) { return _call(args, JS.getCurrentFunction()); }
124         public Object _call(JS.Array args, Function currentFunction) {
125             Trap currentTrap = TrapContext.get().currentTrap;
126             if (args.length() != 0) TrapContext.get().putCascadeHappened = true;
127             Trap t = currentTrap.next;
128             // if we've hit the end of the trap stack, just do a put(,,,true)
129             if (t == null) {
130                 if (args.length() == 0) return currentTrap.trapee.get(currentTrap.name, true);
131                 currentTrap.trapee.put(currentTrap.name, args.elementAt(0), true);
132                 return null;
133             }
134             return t.perform(args);
135         }
136     };
137
138     /** called by Rhino's arguments.trapee hack */
139     public static Object currentTrapee() {
140         Trap current = TrapContext.get().currentTrap;
141         if (current == null) return null;
142         else if (current.rp != null) return current.rp;
143         else return current.trapee;
144     }
145
146     /** called by Rhino's arguments.trapname hack */
147     public static String currentTrapname() {
148         Trap current = TrapContext.get().currentTrap;
149         if (current == null) return null;
150         else return current.name;
151     }
152
153
154     // Instance Methods //////////////////////////////////////////////////////////////////////////
155
156     private Trap() { allTraps.put(myWeak, dummy); }
157
158     /** perform this trap -- arg.length == 0 if this is a get; otherwise it contains a single element to be put */
159     public Object perform(JS.Array args) {
160         TrapContext tc = TrapContext.get();
161
162         // save both thread-locals on the stack and update their values
163         Trap save_currentTrap = tc.currentTrap;
164         tc.currentTrap = this;
165
166         boolean save_putCascadeHappened = tc.putCascadeHappened; 
167         tc.putCascadeHappened = false;
168
169         // invoke the trap function
170         try {
171             if (!isreadtrap && args.length() == 0) return cascadeFunction._call(args, f);
172
173             if (f == null) {
174                 if (Log.verbose) Log.log(this, "debug: reclaimed a dangling trap on property " + name);
175                 Object ret = cascadeFunction._call(args, f);
176                 delete();
177                 return ret;
178             }
179             
180             System.out.println("calling trap on " + name);
181             Object ret = null;
182             try {
183                 ret = f._call(args);
184             } catch (org.xwt.js.ByteCodeBlock.ReturnException re) {
185                 ret = re.retval;
186             }
187             
188             // autocascade if required
189             if (args.length() > 0 && !isreadtrap && !tc.putCascadeHappened) cascadeFunction._call(args, f);
190             
191             return ret;
192
193         } catch (JS.Exn e) {
194             if (Log.on) Log.log(this, e);
195
196         } finally {
197             // restore the thread-locals
198             tc.putCascadeHappened = save_putCascadeHappened;
199             tc.currentTrap = save_currentTrap;
200             tc.trapDepth--;
201         }
202         return null;
203     }
204
205     /** removes this trap */
206     public void delete() {
207         for(Trap last = null, cur = (Trap)trapee.traps.get(name); cur != null; last = cur, cur = cur.next) {
208             if (cur != this) continue;
209             else if (last != null) last.next = cur.next;
210             else if (cur.next == null) trapee.traps.remove(name);
211             else trapee.traps.put(name, cur.next);
212         }
213         if (trapee.surface != null && !trapee.is_trapped("KeyPressed") && !trapee.is_trapped("KeyReleased"))
214             trapee.surface.keywatchers.removeElement(trapee);
215         allTraps.remove(myWeak);
216     }
217
218     /** per-thread storage for Traps */
219     private static class TrapContext {
220
221         private static Hash trapContextByThread = new Hash();
222         private TrapContext() { }
223
224         private boolean putCascadeHappened = false;
225         private Trap currentTrap = null;
226         private int trapDepth = 0;
227
228         /** returns the TrapContext for the current thread */
229         static TrapContext get() {
230             TrapContext ret = (TrapContext)trapContextByThread.get(Thread.currentThread());
231             if (ret == null) {
232                 ret = new TrapContext();
233                 trapContextByThread.put(Thread.currentThread(), ret);
234             }
235             return ret;
236         }
237
238     }
239
240 }
241