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