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