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