disabled clipping code again; it is getting stuck in loops
[org.ibex.core.git] / src / org / ibex / core / Box.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the GNU General Public License version 2 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.core;
6
7 // FIXME: are traps on x/y meaningful?
8 // FIXME: trap on visible, trigger when parent visibility changes
9 // FIXME: mouse move/release still needs to propagate to boxen in which the mouse was pressed and is still held down
10 // FEATURE: reintroduce surface.abort
11
12 // Broken:
13 // - textures
14 // - align/origin
15 // - clipping (all forms)
16
17 import java.util.*;
18 import org.ibex.js.*;
19 import org.ibex.util.*;
20 import org.ibex.plat.*;
21 import org.ibex.graphics.*;
22
23 /**
24  *  <p>
25  *  Encapsulates the data for a single Ibex box as well as all layout
26  *  rendering logic.
27  *  </p>
28  *
29  *  <p>The rendering process consists of four phases; each requires
30  *     one DFS pass over the tree</p>
31  *  <ol><li> <b>pack()</b>: each box sets its childrens' row/col
32  *  <ol><li> <b>constrain()</b>: contentwidth is computed
33  *      <li> <b>resize()</b>: width/height and x/y positions are set
34  *      <li> <b>render()</b>: children draw their content onto the PixelBuffer.
35  *  </ol>
36  *
37  *  The first three passes together are called the <i>reflow</i>
38  *  phase.  Reflowing is done in a seperate pass since SizeChanges
39  *  trigger a Surface.abort; if rendering were done in the same pass,
40  *  rendering work done prior to the Surface.abort would be wasted.
41  */
42 public final class Box extends JS.Obj implements Callable, Mesh.Chain {
43
44     public Mesh.Chain getMeshChainParent() { return parent; }
45     public Mesh       getMesh()            { return mesh; }
46     public Affine     getAffine()          { return transform; }
47
48     // Macros //////////////////////////////////////////////////////////////////////
49
50     final void REPLACE() { for(Box b2 = this; b2 != null && !b2.test(REPLACE); b2 = b2.parent) b2.set(REPLACE); }
51     final void RECONSTRAIN() { for(Box b2 = this; b2 != null && !b2.test(RECONSTRAIN); b2 = b2.parent) b2.set(RECONSTRAIN); }
52
53     //#define CHECKSET_SHORT(prop) short nu = (short)JSU.toInt(value); if (nu == prop) break; prop = nu;
54     //#define CHECKSET_INT(prop) int nu = JSU.toInt(value); if (nu == prop) break; prop = nu;
55     //#define CHECKSET_FLAG(flag) boolean nu=JSU.toBoolean(value);if(nu == test(flag)) break; if (nu) set(flag); else clear(flag);
56     //#define CHECKSET_BOOLEAN.N(prop) boolean nu = JSU.toBoolean(value); if (nu == prop) break; prop = nu;
57     //#define CHECKSET_STRING(prop) if((value==null&&prop==null)||(value!=null&&JSU.toString(value).equals(prop)))break;prop=JSU.toString(value);
58
59     // Instance Data //////////////////////////////////////////////////////////////////////
60
61     private Box          parent       = null;
62     private Box          redirect     = this;
63     private int          flags        = VISIBLE | RECONSTRAIN | REPLACE | STOP_UPWARD_PROPAGATION | CLIP | MOVED;
64     private BalancedTree bt           = null;
65     private String       text         = null;
66     private Font         font         = DEFAULT_FONT; 
67     private Picture      texture      = null;
68     public  int          fillcolor    = 0x00000000;
69     private int          strokecolor  = 0xFF000000;
70     public  float        flex         = 1;
71     private Path         path         = null;
72     private Path         clippath     = null;
73     private Affine       transform    = Affine.identity();
74
75     // FEATURE: polygon caching
76     private Mesh      polygon      = null;
77     private Mesh         mesh         = null;
78
79     // specified directly by user
80     public int minwidth = 0;
81     public int maxwidth = Integer.MAX_VALUE;
82     public int minheight = 0;
83     public int maxheight = Integer.MAX_VALUE;
84
85     // computed during reflow
86     public int width = 0;
87     public int height = 0;
88     public int contentwidth = 0;      // == max(minwidth, textwidth, sum(child.contentwidth))
89     public int contentheight = 0;
90
91
92     // Instance Methods /////////////////////////////////////////////////////////////////////
93
94     /** invoked when a resource needed to render ourselves finishes loading */
95     public Object run(Object o) throws JSExn {
96         if (texture == null) { Log.warn(Box.class, "perform() called with null texture"); return null; }
97         if (texture.isLoaded) {
98             setWidth(max(texture.width, minwidth), maxwidth); 
99             setHeight(max(texture.height, minheight), maxheight); 
100             dirty(); }
101         else { JS res = texture.stream; texture = null; throw new JSExn("image not found: "+res.unclone()); }
102         return null;
103     }
104
105     /** Adds the intersection of (x,y,w,h) and the node's current actual geometry to the Surface's dirty list */
106     public void dirty() { if (path==null) dirty(0, 0, contentwidth, contentheight); else dirty(path); }
107     public void dirty(int x, int y, int w, int h) { }
108     public void dirty(Path p) {
109         Affine a = transform.copy();
110         for(Box cur = this; cur != null; cur = cur.parent) a.premultiply(cur.transform);
111         long hbounds = p.horizontalBounds(a);
112         long vbounds = p.verticalBounds(a);
113         int x1 = (int)Encode.longToFloat2(hbounds);
114         int x2 = (int)Encode.longToFloat1(hbounds);
115         int y1 = (int)Encode.longToFloat2(vbounds);
116         int y2 = (int)Encode.longToFloat1(vbounds);
117         if (getSurface() != null) getSurface().dirty(x1, y1, x2-x1, y2-y1);
118     }
119
120
121     // Reflow ////////////////////////////////////////////////////////////////////////////////////////
122
123     /** should only be invoked on the root box */
124     public void reflow() {
125         constrain(this, Affine.identity());
126         width = maxwidth;
127         height = maxheight;
128         transform.e = 0;
129         transform.f = 0;
130         place();
131     }
132
133     void place() {
134         if (!packed()) {
135             for(Box child = getChild(0); child != null; child = child.nextSibling()) {
136                 child.width = max(child.minwidth, min(child.test(HSHRINK) ? child.contentwidth : width, child.maxwidth));
137                 child.height = max(child.minheight, min(child.test(VSHRINK) ? child.contentheight : height, child.maxheight));
138                 child.place();
139             }
140             return;
141         }
142         float slack = width, oldslack = 0, flex = 0, newflex = 0;
143         for(Box child = getChild(0); child != null; child = child.nextSibling()) {
144             if (!child.test(VISIBLE)) continue;
145             slack -= (child.width = child.contentwidth);
146             if (child.width < (child.test(HSHRINK)?child.contentwidth:child.maxwidth)) flex += child.flex;
147             child.height = child.test(HSHRINK) ? child.contentheight : bound(child.contentheight, height, child.maxheight);
148         }
149         while(slack > 0 && flex > 0 && oldslack!=slack) {
150             oldslack = slack;
151             slack = width;
152             for(Box child = getChild(0); child != null; child = child.nextSibling()) {
153                 if (!child.test(VISIBLE)) continue;
154                 if (child.width < child.maxwidth && !child.test(HSHRINK))
155                     child.width = bound(child.contentwidth, (int)(child.width + (slack/flex)), child.maxwidth);
156                 newflex += child.width < child.maxwidth && !child.test(HSHRINK) ? child.flex : 0;
157                 slack -= child.width;
158             }
159             flex = newflex;
160         }
161         float pos = slack / 2;
162         for(Box child = getChild(0); child != null; child = child.nextSibling()) {
163             if (!child.test(VISIBLE)) continue;
164             child.transform.e += pos;
165             child.transform.f += (height-child.height)/2;
166             pos += child.width;
167             child.place();
168         }
169     }
170     
171     /** used (single-threadedly) in constrain() */
172     private static int xmin = 0, ymin = 0, xmax = 0, ymax = 0;
173     public void constrain(Box b, Affine a) {
174         contentwidth = 0;
175         contentheight = 0;
176         transform.e = 0;
177         transform.f = 0;
178         a = a.copy().premultiply(transform);
179
180         //boolean relevant = packed() || ((fillcolor&0xff000000)!=0x0) || path!=null;
181         boolean relevant = true;
182         int save_xmin = xmin, save_ymin = ymin, save_xmax = xmax, save_ymax = ymax;
183         if (!relevant) {
184             for(Box child = getChild(0); child != null; child = child.nextSibling()) {
185                 child.constrain(b, a);
186                 contentwidth = max(contentwidth, child.contentwidth);
187                 contentheight = max(contentheight, child.contentheight);
188             }
189             return;
190         }
191
192         for(Box child = getChild(0); child != null; child = child.nextSibling()) {
193             xmin = Integer.MAX_VALUE; ymin = Integer.MAX_VALUE;
194             xmax = Integer.MIN_VALUE; ymax = Integer.MIN_VALUE;
195             child.constrain(this, Affine.identity());
196             if (xmin==Integer.MAX_VALUE||xmax==Integer.MIN_VALUE||ymin==Integer.MAX_VALUE||ymax== Integer.MIN_VALUE) continue;
197             child.transform.e = -1 * xmin;
198             child.transform.f = -1 * ymin;
199             contentwidth += (xmax-xmin);
200             contentheight = max(ymax-ymin, contentheight);
201         }
202         xmin = save_xmin;
203         ymin = save_ymin;
204         xmax = save_xmax;
205         ymax = save_ymax;
206
207         int cw = contentwidth = bound(minwidth, contentwidth, maxwidth);
208         int ch = contentheight = bound(minheight, contentheight, maxheight);
209         //#repeat contentwidth/contentheight contentheight/contentwidth minwidth/minheight row/col col/row \
210         //        textwidth/textheight maxwidth/maxheight bounds/boundsy x1/y1 x2/y2 z1/q1 z2/q2 z3/q3 z4/q4 \
211         //        horizontalBounds/verticalBounds e/f multiply_px/multiply_py xmin/ymin xmax/ymax
212         long bounds = path==null ? 0                     : path.horizontalBounds(a);
213         float z1    = path==null ? a.multiply_px(0, 0)   : Encode.longToFloat2(bounds);
214         float z2    = path==null ? a.multiply_px(cw, ch) : Encode.longToFloat1(bounds);
215         float z3    = path==null ? a.multiply_px(cw, 0)  : Encode.longToFloat2(bounds);
216         float z4    = path==null ? a.multiply_px(0, ch)  : Encode.longToFloat1(bounds);
217         xmin = min(xmin, (int)min(min(z1, z2), min(z3, z4)));
218         xmax = max(xmax, (int)max(max(z1, z2), max(z3, z4)));
219         //#end
220     }
221     
222
223     // Rendering Pipeline /////////////////////////////////////////////////////////////////////
224
225     private static final boolean OPTIMIZE = false;
226
227     /** Renders self and children within the specified region. All rendering operations are clipped to xIn,yIn,wIn,hIn */
228     public void render(PixelBuffer buf, Affine a, Mesh clipFrom) { render(buf, a, clipFrom, Affine.identity()); }
229     public void render(PixelBuffer buf, Affine a, Mesh clipFrom, Affine clipa) {
230         if (!test(VISIBLE)) return;
231         a = a.copy().multiply(transform);
232         clipa = clipa.copy().multiply(transform);
233
234         if (mesh == null)
235             if (path != null) mesh = new Mesh(path, true);
236             else {
237                 if (((fillcolor & 0xFF000000) != 0x00000000 || parent == null) && (text==null||"".equals(text)))
238                     mesh = new Mesh().addRect(0, 0, contentwidth, contentheight);
239                 // long ret = font.rasterizeGlyphs(text, buf, a, null, 0x777777, 0);
240                 // minwidth = maxwidth = font.textwidth(text);
241                 // minheight = maxheight = font.textwidth(text);
242                 // if (ret == 0) Platform.Scheduler.add(this);
243                 // FIXME: texture
244             }
245         if (mesh==null) {
246             for(Box b = getChild(0); b != null; b = b.nextSibling()) b.render(buf, a, clipFrom, clipa);
247             return;
248         }
249
250         // FIXME: mesh clipping code has been getting stuck in loops; to see this,
251         //        uncomment the next two lines and swap the order of the last two lines.
252
253         //if (clipFrom != null) clipFrom.subtract(mesh, clipa);
254         //Mesh mesh = treeSize() > 0 ? this.mesh.copy() : this.mesh;
255         mesh.fill(buf, a, null, fillcolor, true);
256         for(Box b = getChild(0); b != null; b = b.nextSibling()) b.render(buf, a, mesh, Affine.identity());
257     }
258     
259     // Methods to implement org.ibex.js.JS //////////////////////////////////////
260   
261     public JS call(JS method, JS[] args) throws JSExn {
262         switch (args.length) {
263             case 1: {
264                 //#switch(JSU.toString(method))
265                 case "indexof":
266                     Box b = (Box)args[0];
267                     if (b.parent != this)
268                         return (redirect == null || redirect == this) ? JSU.N(-1) : redirect.call(method, args);
269                     return JSU.N(b.getIndexInParent());
270
271                 case "distanceto":
272                     Box b = (Box)args[0];
273                     JS ret = new JS.Obj();
274                     ret.put(JSU.S("x"), JSU.N(b.localToGlobalX(0) - localToGlobalX(0)));
275                     ret.put(JSU.S("y"), JSU.N(b.localToGlobalY(0) - localToGlobalY(0)));
276                     return ret;
277
278                 //#end
279             }
280         }
281         return super.call(method, args);
282     }
283
284     public JS get(JS name) throws JSExn {
285         if (JSU.isInt(name))
286             return redirect == null ? null : redirect == this ? getChild(JSU.toInt(name)) : redirect.get(name);
287
288         //#switch(JSU.toString(name))
289         case "surface": return parent == null ? null : parent.getAndTriggerTraps(name);
290         case "indexof": return METHOD;
291         case "distanceto": return METHOD;
292         case "text": return JSU.S(text);
293         case "path": {
294             if (path != null) return JSU.S(path.toString());
295             if (text == null) return null;
296             if (font == null) return null;
297             String ret = "";
298             for(int i=0; i<text.length(); i++) ret += font.glyphs[text.charAt(i)].path;
299             return JSU.S(ret);
300         }
301         case "fill": return JSU.S(Color.colorToString(fillcolor));
302         case "strokecolor": return JSU.S(Color.colorToString(strokecolor));
303         case "textcolor": return JSU.S(Color.colorToString(strokecolor));
304         case "font": return font == null ? null : font.stream;
305         case "fontsize": return font == null ? JSU.N(10) : JSU.N(font.pointsize);
306         case "thisbox": return this;
307         case "shrink": return JSU.B(test(HSHRINK) || test(VSHRINK));
308         case "hshrink": return JSU.B(test(HSHRINK));
309         case "vshrink": return JSU.B(test(VSHRINK));
310         case "flex": return JSU.N(flex);
311         case "width": getRoot().reflow(); return JSU.N(width);
312         case "height": getRoot().reflow(); return JSU.N(height);
313         case "minwidth": return JSU.N(minwidth);
314         case "maxwidth": return JSU.N(maxwidth);
315         case "minheight": return JSU.N(minheight);
316         case "maxheight": return JSU.N(maxheight);
317         case "clip": return JSU.B(test(CLIP));
318         case "visible": return JSU.B(test(VISIBLE) && (parent == null || (parent.get(JSU.S("visible")) == JSU.T)));
319         case "axis": return test(XAXIS) ? JSU.S("x") : test(YAXIS) ? JSU.S("y") : JSU.S("z");
320         case "globalx": return JSU.N(localToGlobalX(0));
321         case "globaly": return JSU.N(localToGlobalY(0));
322         case "cursor": return test(CURSOR) ? JSU.S((String)boxToCursor.get(this)) : null;
323         case "mouse":
324             if (getSurface() == null) return null;
325             if (getSurface()._mousex == Integer.MAX_VALUE)
326                 throw new JSExn("you cannot read from the box.mouse property in background thread context");
327             return new Mouse();
328         case "numchildren": return redirect == null ? JSU.N(0) : redirect == this ? JSU.N(treeSize()) : redirect.get(JSU.S("numchildren"));
329         case "redirect": return redirect == null ? null : redirect == this ? JSU.T : redirect.get(JSU.S("redirect"));
330         case "Minimized": if (parent == null && getSurface() != null) return JSU.B(getSurface().minimized);
331         default: return super.get(name);
332         //#end
333         throw new Error("unreachable"); // unreachable
334     }
335
336     private class Mouse extends JS.Immutable implements JS.Cloneable {
337         public JS get(JS key) throws JSExn {
338             //#switch(JSU.toString(key))
339             case "x": return JSU.N(globalToLocalX(getSurface()._mousex));
340             case "y": return JSU.N(globalToLocalY(getSurface()._mousey));
341
342             // this might not get recomputed if we change mousex/mousey...
343             case "inside": return JSU.B(test(MOUSEINSIDE));
344             //#end
345             return super.get(key);
346         }
347     }
348
349     //#repeat setWidth/setHeight minwidth/minheight maxwidth/maxheight pendingWidth/pendingHeight
350     public void setWidth(int min, int max) {
351         // FIXME: deal with conflicting min/max
352         if (this.minwidth == min && this.maxwidth == max) return;
353         this.minwidth = min;
354         this.maxwidth = max;
355         RECONSTRAIN();
356         if (parent != null || getSurface() == null) return;
357         getSurface().pendingWidth = maxwidth;
358
359         // FIXME: the repeat doesn't work right here
360         getSurface().setMinimumSize(minwidth, minheight, minwidth != maxwidth || minheight != maxheight);
361     }
362     //#end
363
364     public void put(JS name, JS value) throws JSExn {
365         if (JSU.isInt(name)) { put(JSU.toInt(name), value); return; }
366         //#switch(JSU.toString(name))
367         case "thisbox":     if (value == null) removeSelf();
368         case "text":        {
369             String s = value==null ?  "" : JSU.toString(value);
370             text = s;
371             minwidth = maxwidth = font.textwidth(text);
372             System.out.println("width=" + width);
373             minheight = maxheight = font.textheight(text);
374             System.out.println("height=" + height);
375             RECONSTRAIN();
376             dirty();
377         }
378         case "strokecolor": value = JSU.N(Color.stringToColor(JSU.toString(value))); CHECKSET_INT(strokecolor); dirty();
379         case "textcolor":   value = JSU.N(Color.stringToColor(JSU.toString(value))); CHECKSET_INT(strokecolor); dirty();
380         case "shrink":      CHECKSET_FLAG(HSHRINK | VSHRINK); RECONSTRAIN();
381         case "hshrink":     CHECKSET_FLAG(HSHRINK); RECONSTRAIN();
382         case "vshrink":     CHECKSET_FLAG(VSHRINK); RECONSTRAIN();
383         case "path":        {
384             mesh = null;
385             path = new Path(JSU.toString(value));
386             float tx = -1 * Encode.longToFloat2(path.horizontalBounds(Affine.identity()));
387             float ty = -1 * Encode.longToFloat2(path.verticalBounds(Affine.identity()));
388             path.transform(Affine.translate(tx, ty), true);
389             REPLACE();
390             RECONSTRAIN();
391             dirty();
392             polygon = null;
393         }
394         case "clippath":        {
395             clippath = new Path(JSU.toString(value));
396             //float tx = -1 * Encode.longToFloat2(clippath.horizontalBounds(Affine.identity()));
397             //float ty = -1 * Encode.longToFloat2(clippath.verticalBounds(Affine.identity()));
398             //clippath.transform(Affine.translate(tx, ty), true);
399             REPLACE();
400             RECONSTRAIN();
401             dirty();
402             polygon = null;
403         }
404         case "transform":   {
405             transform = Affine.parse(JSU.toString(value));
406             transform.e = 0;
407             transform.f = 0;
408             if (getSurface() != null)  // FIXME
409                 getSurface().dirty(0, 0, getSurface().root.contentwidth, getSurface().root.contentheight);
410             REPLACE();
411             RECONSTRAIN(); dirty(); polygon = null;
412         }
413         case "width":       setWidth(JSU.toInt(value), JSU.toInt(value));
414         case "height":      setHeight(JSU.toInt(value), JSU.toInt(value));
415         case "flex":        flex = JSU.toFloat(value);
416         case "maxwidth":    setWidth(minwidth, JSU.toInt(value));
417         case "minwidth":    setWidth(JSU.toInt(value), maxwidth);
418         case "maxheight":   setHeight(minheight, JSU.toInt(value));
419         case "minheight":   setHeight(JSU.toInt(value), maxheight);
420         case "visible":     CHECKSET_FLAG(VISIBLE); RECONSTRAIN(); dirty();
421         case "cursor":      setCursor(JSU.toString(value));
422         case "fill":        setFill(value);
423         case "clip":        CHECKSET_FLAG(CLIP); if (parent == null) dirty(); else parent.dirty();
424         case "mouse":
425             int mousex = JSU.toInt(((JS)value).get(JSU.S("x")));
426             int mousey = JSU.toInt(((JS)value).get(JSU.S("y")));
427             getSurface()._mousex = (int)localToGlobalX(mousex);
428             getSurface()._mousey = (int)localToGlobalY(mousey);
429         case "axis":        {
430             String s = JSU.toString(value); 
431             if (s.equals("x")) { clear(YAXIS); set(XAXIS); }
432             else if (s.equals("y")) { clear(XAXIS); set(YAXIS); }
433             else if (s.equals("z")) { clear(XAXIS); clear(YAXIS); }
434             else JSU.warn("attempted to set axis property to invalid value: " + s);
435         }
436         case "Minimized": if (parent == null && getSurface() != null) getSurface().minimized = JSU.toBoolean(value);  // FEATURE
437         case "Maximized": if (parent == null && getSurface() != null) getSurface().maximized = JSU.toBoolean(value);  // FEATURE
438         case "Close":     if (parent == null && getSurface() != null) getSurface().dispose(true);
439         case "redirect":
440             for(Box cur = (Box)value; cur != null || cur == redirect; cur = cur.parent)
441                 if (cur == redirect) { redirect = (Box)value; return; }
442             JSU.error("redirect can only be set to a descendant of its current value");
443         case "fontsize": font = Font.getFont(font == null ? null : font.stream, JSU.toInt(value)); RECONSTRAIN(); dirty();
444         case "font":
445             if(!(value instanceof Fountain)) throw new JSExn("You can only put streams to the font property");
446             //FIXME: if (font == value) return;  // FIXME: unclone()
447             font = value == null ? null : Font.getFont((Fountain)value, font == null ? 10 : font.pointsize);
448             RECONSTRAIN();
449             dirty();
450         case "titlebar": if (getSurface()!=null) getSurface().setTitleBarText(JSU.toString(value)); super.put(name,value);
451         // FIXME: icon
452
453         case "Press1":        if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
454         case "Press2":        if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
455         case "Press3":        if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
456         case "Release1":      if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
457         case "Release2":      if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
458         case "Release3":      if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
459         case "Click1":        if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
460         case "Click2":        if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
461         case "Click3":        if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
462         case "DoubleClick1":  if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
463         case "DoubleClick2":  if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
464         case "DoubleClick3":  if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
465         case "KeyPressed":    if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
466         case "KeyReleased":   if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
467         case "Move":          if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
468         case "HScroll":       if (!test(STOP_UPWARD_PROPAGATION) && parent != null)
469             parent.putAndTriggerTraps(name, JSU.N(JSU.toFloat(value) * ((float)parent.fontSize()) / ((float)fontSize())));
470         case "VScroll":       if (!test(STOP_UPWARD_PROPAGATION) && parent != null)
471             parent.putAndTriggerTraps(name, JSU.N(JSU.toFloat(value) * ((float)parent.fontSize()) / ((float)fontSize())));
472
473         case "_Move":         propagateDownward(name, value, false);
474         case "_Press1":       propagateDownward(name, value, false);
475         case "_Press2":       propagateDownward(name, value, false);
476         case "_Press3":       propagateDownward(name, value, false);
477         case "_Release1":     propagateDownward(name, value, false);
478         case "_Release2":     propagateDownward(name, value, false);
479         case "_Release3":     propagateDownward(name, value, false);
480         case "_Click1":       propagateDownward(name, value, false);
481         case "_Click2":       propagateDownward(name, value, false);
482         case "_Click3":       propagateDownward(name, value, false);
483         case "_DoubleClick1": propagateDownward(name, value, false);
484         case "_DoubleClick2": propagateDownward(name, value, false);
485         case "_DoubleClick3": propagateDownward(name, value, false);
486         case "_KeyPressed":   propagateDownward(name, value, false);
487         case "_KeyReleased":  propagateDownward(name, value, false);
488         case "_HScroll":      propagateDownward(name, value, false);
489         case "_VScroll":      propagateDownward(name, value, false);
490
491         case "SizeChange":    return;
492         case "ChildChange":   return;
493         case "Enter":         return;
494         case "Leave":         return;
495
496         default:              super.put(name, value);
497         //#end
498     }
499
500     private void setCursor(String value) throws JSExn {
501         if (value == null) { clear(CURSOR); boxToCursor.remove(this); return; }
502         if (value.equals(boxToCursor.get(this))) return;
503         set(CURSOR);
504         boxToCursor.put(this, value);
505         Surface surface = getSurface();
506         if (surface == null) return;
507         String tempcursor = surface.cursor;
508         propagateDownward(null, null, false);
509         if (surface.cursor != tempcursor) surface.syncCursor();
510     }
511
512     private void setFill(JS value) throws JSExn {
513         if (value == null) {
514             if (texture == null && fillcolor == 0) return;
515             texture = null;
516             fillcolor = 0;
517         } else if (JSU.isString(value)) {
518             int newfillcolor = Color.stringToColor(JSU.toString(value));
519             if (newfillcolor == fillcolor) return;
520             fillcolor = newfillcolor;
521             texture = null;
522         } else {
523             Picture newtex = Picture.load((JS)value, this);
524             if (texture == newtex) return;
525             texture = newtex;
526             fillcolor = 0;
527             if (texture != null && texture.isLoaded) run(null);
528         }
529         dirty();
530     }
531
532     /**
533      *  Handles events which propagate down the box tree.  If obscured
534      *  is set, then we merely check for Enter/Leave.
535      */
536     private void propagateDownward(JS name_, JS value, boolean obscured) throws JSExn {
537
538         String name = JSU.toString(name_);
539         if (getSurface() == null) return;
540         int x = (int)globalToLocalX(getSurface()._mousex);
541         int y = (int)globalToLocalY(getSurface()._mousey);
542         boolean wasinside = test(MOUSEINSIDE);
543         boolean isinside = test(VISIBLE) && inside(x, y) && !obscured;
544         if (!wasinside && isinside) {
545             set(MOUSEINSIDE);
546             putAndTriggerTrapsAndCatchExceptions(JSU.S("Enter"), JSU.T);
547         }
548         if (isinside && test(CURSOR)) getSurface().cursor = (String)boxToCursor.get(this);
549         if (wasinside && !isinside) {
550             clear(MOUSEINSIDE);
551             putAndTriggerTrapsAndCatchExceptions(JSU.S("Leave"), JSU.T);
552         }
553
554         boolean found = false;
555         if (wasinside || isinside)
556             for(Box child = getChild(treeSize() - 1); child != null; child = child.prevSibling()) {
557                 boolean save_stop = child.test(STOP_UPWARD_PROPAGATION);
558                 JS value2 = value;
559                 if (name.equals("_HScroll") || name.equals("_VScroll"))
560                     value2 = JSU.N(JSU.toFloat(value) * ((float)child.fontSize()) / (float)fontSize());
561                 if (obscured /*|| !child.inside(x - child.x, y - child.y) FIXME FIXME */) {
562                     child.propagateDownward(name_, value2, true);
563                 } else try {
564                     found = true;
565                     child.clear(STOP_UPWARD_PROPAGATION);
566                     if (name != null) child.putAndTriggerTrapsAndCatchExceptions(name_, value2);
567                     else child.propagateDownward(name_, value2, obscured);
568                 } finally {
569                     if (save_stop) child.set(STOP_UPWARD_PROPAGATION); else child.clear(STOP_UPWARD_PROPAGATION);
570                 }
571                 /* FIXME FIXME
572                 if (child.inside(x - child.x, y - child.y))
573                     if (name != null && name.equals("_Move")) obscured = true;
574                     else break;
575  */
576             }
577
578         if (!obscured && !found)
579             if ("_Move".equals(name) || name.startsWith("_Release") || wasinside)
580                 if (name != null)
581                     putAndTriggerTrapsAndCatchExceptions(JSU.S(name.substring(1)), value);
582     }
583
584     /** figures out what box in this subtree of the Box owns the pixel at x,y relitave to the Surface */
585     public static Box whoIs(Box cur, int x, int y) {
586
587         if (cur.parent != null) throw new Error("whoIs may only be invoked on the root box of a surface");
588         int globalx = 0;
589         int globaly = 0;
590
591         // WARNING: this method is called from the event-queueing thread -- it may run concurrently with
592         // ANY part of Ibex, and is UNSYNCHRONIZED for performance reasons.  BE CAREFUL HERE.
593
594         if (!cur.test(VISIBLE)) return null;
595         if (!cur.inside(x - globalx, y - globaly)) return cur.parent == null ? cur : null;
596         OUTER: while(true) {
597             for(int i=cur.treeSize() - 1; i>=0; i--) {
598                 Box child = cur.getChild(i);
599                 if (child == null) continue;        // since this method is unsynchronized, we have to double-check
600                 globalx += child.transform.e;
601                 globaly += child.transform.f;
602                 if (child.test(VISIBLE) && child.inside(x - globalx, y - globaly)) { cur = child; continue OUTER; }
603                 globalx -= child.transform.e;
604                 globaly -= child.transform.f;
605             }
606             break;
607         }
608         return cur;
609     }
610
611
612     // Trivial Helper Methods (should be inlined) /////////////////////////////////////////
613
614     public final int fontSize() { return font == null ? DEFAULT_FONT.pointsize : font.pointsize; }
615     public Enumeration keys() { throw new Error("you cannot apply for..in to a " + this.getClass().getName()); }
616     public Box getRoot() { return parent == null ? this : parent.getRoot(); }
617     public Surface getSurface() { return Surface.fromBox(getRoot()); }
618     private final boolean packed() { return test(YAXIS) || test(XAXIS); }
619     Box nextPackedSibling() { Box b = nextSibling(); return b == null || (b.packed() && b.test(VISIBLE))?b:b.nextPackedSibling(); }
620     Box firstPackedChild() { Box b = getChild(0); return b == null || (b.packed() && b.test(VISIBLE))?b:b.nextPackedSibling(); }
621     public float globalToLocalX(float x) { return parent == null ? x : parent.globalToLocalX(x - transform.e); }
622     public float globalToLocalY(float y) { return parent == null ? y : parent.globalToLocalY(y - transform.f); }
623     public float localToGlobalX(float x) { return parent == null ? x : parent.globalToLocalX(x + transform.e); }
624     public float localToGlobalY(float y) { return parent == null ? y : parent.globalToLocalY(y + transform.f); }
625
626     static short min(short a, short b) { if (a<b) return a; else return b; }
627     static int min(int a, int b) { if (a<b) return a; else return b; }
628     static float min(float a, float b) { if (a<b) return a; else return b; }
629
630     static short max(short a, short b) { if (a>b) return a; else return b; }
631     static int max(int a, int b) { if (a>b) return a; else return b; }
632     static float max(float a, float b) { if (a>b) return a; else return b; }
633
634     static int min(int a, int b, int c) { if (a<=b && a<=c) return a; else if (b<=c && b<=a) return b; else return c; }
635     static int max(int a, int b, int c) { if (a>=b && a>=c) return a; else if (b>=c && b>=a) return b; else return c; }
636     static int bound(int a, int b, int c) { if (c < b) return c; if (a > b) return a; return b; }
637     final boolean inside(int x, int y) { return test(VISIBLE) && x >= 0 && y >= 0 && x < width && y < height; }
638
639     void set(int mask) { flags |= mask; }
640     void set(int mask, boolean setclear) { if (setclear) set(mask); else clear(mask); }
641     void clear(int mask) { flags &= ~mask; }
642     public boolean test(int mask) { return ((flags & mask) == mask); }
643     
644
645     // Tree Handling //////////////////////////////////////////////////////////////////////
646
647     public final int getIndexInParent() { return parent == null ? 0 : parent.indexNode(this); }
648     public final Box nextSibling() { return parent == null ? null : parent.getChild(parent.indexNode(this) + 1); }
649     public final Box prevSibling() { return parent == null ? null : parent.getChild(parent.indexNode(this) - 1); }
650     public final Box getChild(int i) {
651         if (i < 0) return null;
652         if (i >= treeSize()) return null;
653         return (Box)getNode(i);
654     }
655
656     // Tree Manipulation /////////////////////////////////////////////////////////////////////
657
658     public void removeSelf() {
659         if (parent != null) { parent.removeChild(parent.indexNode(this)); return; }
660         Surface surface = Surface.fromBox(this); 
661         if (surface != null) surface.dispose(true);
662     }
663
664     /** remove the i^th child */
665     public void removeChild(int i) {
666         Box b = getChild(i);
667         b.RECONSTRAIN();
668         b.dirty();
669         b.clear(MOUSEINSIDE);
670         deleteNode(i);
671         b.parent = null;
672         RECONSTRAIN();
673         putAndTriggerTrapsAndCatchExceptions(JSU.S("ChildChange"), b);
674     }
675     
676     public void put(int i, JS value) throws JSExn {
677         if (i < 0) return;
678             
679         if (value != null && !(value instanceof Box)) {
680             if (Log.on) JSU.warn("attempt to set a numerical property on a box to a non-box");
681             return;
682         }
683
684         if (redirect == null) {
685             if (value == null) putAndTriggerTrapsAndCatchExceptions(JSU.S("ChildChange"), getChild(i));
686             else JSU.warn("attempt to add/remove children to/from a node with a null redirect");
687
688         } else if (redirect != this) {
689             if (value != null) putAndTriggerTrapsAndCatchExceptions(JSU.S("ChildChange"), value);
690             redirect.put(i, value);
691             if (value == null) {
692                 Box b = (Box)redirect.get(JSU.N(i));
693                 if (b != null) putAndTriggerTrapsAndCatchExceptions(JSU.S("ChildChange"), b);
694             }
695
696         } else if (value == null) {
697             if (i < 0 || i > treeSize()) return;
698             Box b = getChild(i);
699             removeChild(i);
700             putAndTriggerTrapsAndCatchExceptions(JSU.S("ChildChange"), b);
701
702         } else {
703             Box b = (Box)value;
704
705             // check if box being moved is currently target of a redirect
706             for(Box cur = b.parent; cur != null; cur = cur.parent)
707                 if (cur.redirect == b) {
708                     if (Log.on) JSU.warn("attempt to move a box that is the target of a redirect");
709                     return;
710                 }
711
712             // check for recursive ancestor violation
713             for(Box cur = this; cur != null; cur = cur.parent)
714                 if (cur == b) {
715                     if (Log.on) JSU.warn("attempt to make a node a parent of its own ancestor");
716                     if (Log.on) Log.info(this, "box == " + this + "  ancestor == " + b);
717                     return;
718                 }
719
720             if (b.parent != null) b.parent.removeChild(b.parent.indexNode(b));
721             insertNode(i, b);
722             b.parent = this;
723             
724             // need both of these in case child was already uncalc'ed
725             b.RECONSTRAIN();
726             RECONSTRAIN();
727             
728             b.dirty(); 
729             putAndTriggerTrapsAndCatchExceptions(JSU.S("ChildChange"), b);
730         }
731     }
732     
733     public void putAndTriggerTrapsAndCatchExceptions(JS name, JS val) {
734         try {
735             putAndTriggerTraps(name, val);
736         } catch (JSExn e) {
737             JSU.log("caught js exception while putting to trap \""+ JSU.str(name)+"\"");
738             JSU.log(e);
739         } catch (Exception e) {
740             JSU.log("caught exception while putting to trap \""+ JSU.str(name)+"\"");
741             JSU.log(e);
742         }
743     }
744     
745     // BalancedTree functions
746     private void insertNode(int p, Box b) { if(bt == null) bt = new BalancedTree(); bt.insertNode(p,b); }
747     private int treeSize() { return bt == null ? 0 : bt.treeSize(); }
748     private int indexNode(Box b) { return bt == null ? -1 : bt.indexNode(b); }
749     private void deleteNode(int p) { bt.deleteNode(p); }
750     private Box getNode(int p) { return (Box)bt.getNode(p); }
751
752     // FIXME memory leak
753     final static JS.Method METHOD = new JS.Method();
754     final static Basket.Map boxToCursor = new Basket.Hash(500, 3);
755     final static JS SIZECHANGE = JSU.S("SizeChange");
756     final static Font DEFAULT_FONT = Font.getFont(Main.vera, 10);
757
758
759     // Flags //////////////////////////////////////////////////////////////////////
760
761     public static final int MOUSEINSIDE             = 0x00000001;
762     public static final int XAXIS                   = 0x00000002;
763     public static final int YAXIS                   = 0x00000004;
764     public static final int VISIBLE                 = 0x00000008;
765     public static final int VSHRINK                 = 0x00000010;
766     public static final int HSHRINK                 = 0x00000020;
767     public static final int RECONSTRAIN             = 0x00000040;
768     public static final int REPLACE                 = 0x00000080;
769
770     // if true, this box has cursor in the cursor hash; FEATURE: GC issues?
771     public static final int CURSOR                  = 0x00010000;
772     public static final int CLIP                    = 0x00020000;
773     public static final int STOP_UPWARD_PROPAGATION = 0x00040000;
774     public static final int MOVED                   = 0x00080000;
775
776
777 }