Full fix for Bug 471
[org.ibex.core.git] / src / org / ibex / Box.java
1 // FIXME
2 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
3 package org.ibex;
4
5 // FEATURE: reflow before allowing js to read from width/height 
6 // FEATURE: fastpath for rows=1/cols=1
7 // FEATURE: mark to reflow starting with a certain child
8 // FEATURE: separate mark_for_reflow and mark_for_resize
9 // FEATURE: make all methods final
10 // FEATURE: use a linked list for the "frontier" when packing
11 // FEATURE:    or else have a way to mark a column "same as last one"?
12 // FEATURE: reintroduce surface.abort
13
14 import java.util.*;
15 import org.ibex.js.*;
16 import org.ibex.util.*;
17 import org.ibex.translators.*;
18
19 /**
20  *  <p>
21  *  Encapsulates the data for a single Ibex box as well as all layout
22  *  rendering logic.
23  *  </p>
24  *
25  *  <p>The rendering process consists of four phases; each requires
26  *     one DFS pass over the tree</p>
27  *  <ol><li> <b>repacking</b>: children of a box are packed into columns
28  *           and rows according to their colspan/rowspan attributes and
29  *           ordering.
30  *  <ol><li> <b>reconstraining</b>: Minimum and maximum sizes of columns are computed.
31  *      <li> <b>resizing</b>: width/height and x/y positions of children
32  *           are assigned, and PosChange/SizeChanges are triggered.
33  *      <li> <b>repainting</b>: children draw their content onto the PixelBuffer.
34  *  </ol>
35  *
36  *  The first three passes together are called the <i>reflow</i> phase.
37  *  Reflowing is done in a seperate pass since PosChanges and
38  *  SizeChanges trigger an Surface.abort; if rendering were done in the same
39  *  pass, rendering work done prior to the Surface.abort would be wasted.
40  */
41 public final class Box extends JSScope implements Scheduler.Task {
42
43     // Macros //////////////////////////////////////////////////////////////////////
44
45     //#define LENGTH int
46     //#define MARK_REPACK for(Box b2 = this; b2 != null && !b2.test(REPACK); b2 = b2.parent) b2.set(REPACK);
47     //#define MARK_REPACK_b for(Box b2 = b; b2 != null && !b2.test(REPACK); b2 = b2.parent) b2.set(REPACK);
48     //#define MARK_REPACK_parent for(Box b2 = parent; b2 != null && !b2.test(REPACK); b2 = b2.parent) b2.set(REPACK);
49     //#define MARK_REFLOW for(Box b2 = this; b2 != null && !b2.test(REFLOW); b2 = b2.parent) b2.set(REFLOW);
50     //#define MARK_REFLOW_b for(Box b2 = b; b2 != null && !b2.test(REFLOW); b2 = b2.parent) b2.set(REFLOW);
51     //#define MARK_RESIZE for(Box b2 = this; b2 != null && !b2.test(RESIZE); b2 = b2.parent) b2.set(RESIZE);
52     //#define MARK_RESIZE_b for(Box b2 = b; b2 != null && !b2.test(RESIZE); b2 = b2.parent) b2.set(RESIZE);
53     //#define CHECKSET_SHORT(prop) short nu = (short)toInt(value); if (nu == prop) break; prop = nu;
54     //#define CHECKSET_INT(prop) int nu = toInt(value); if (nu == prop) break; prop = nu;
55     //#define CHECKSET_FLAG(flag) boolean nu = toBoolean(value); if (nu == test(flag)) break; if (nu) set(flag); else clear(flag);
56     //#define CHECKSET_BOOLEAN(prop) boolean nu = toBoolean(value); if (nu == prop) break; prop = nu;
57     //#define CHECKSET_STRING(prop) if ((value==null&&prop==null)||(value!=null&&value.equals(prop))) break; prop=(String)value;
58
59     void mark_for_repack() { MARK_REPACK; }
60
61     protected Box() { super(null); }
62
63     static Hash boxToCursor = new Hash(500, 3);
64     public static final int MAX_LENGTH = Integer.MAX_VALUE;
65     static final Font DEFAULT_FONT;
66    
67     static {
68         Font f = null;
69         try { f = Font.getFont((Stream)Main.builtin.get("fonts/vera/Vera.ttf"), 10); }
70         catch(JSExn e) { Log.info(Box.class, "should never happen: "+e); }
71         DEFAULT_FONT = f;
72     }
73
74     // FIXME update these
75     // box properties can not be trapped
76     static final String[] props = new String[] {
77         "shrink", "hshrink", "vshrink", "x", "y", "width", "height", "cols", "rows",
78         "colspan", "rowspan", "align", "visible", "packed", "globalx", "globaly",
79         "minwidth", "maxwidth", "minheight", "maxheight", "indexof", "thisbox", "clip",
80         "numchildren", "redirect", "cursor", "mouse"
81     };
82
83     // FIXME update these
84     // events can have write traps, but not read traps
85     static final String[] events = new String[] {
86         "Press1", "Press2", "Press3",
87         "Release1", "Release2", "Release3",
88         "Click1", "Click2", "Click3",
89         "DoubleClick1", "DoubleClick2", "DoubleClick3",
90         "Enter", "Leave", "Move", 
91         "KeyPressed", "KeyReleased", "PosChange", "SizeChange",
92         "childadded", "childremoved",
93         "Focused", "Maximized", "Minimized", "Close",
94         "icon", "titlebar", "toback", "tofront"
95     };
96
97     // Flags //////////////////////////////////////////////////////////////////////
98
99     static final int MOUSEINSIDE  = 0x00000001;
100     static final int VISIBLE      = 0x00000002;
101     static final int PACKED       = 0x00000004;
102     static final int HSHRINK      = 0x00000008;
103     static final int VSHRINK      = 0x00000010;
104     static final int BLACK        = 0x00000020;  // for red-black code
105
106     static final int FIXED        = 0x00000040;
107     static final boolean ROWS     = true;
108     static final boolean COLS     = false;
109
110     static final int ISROOT       = 0x00000080;
111     static final int REPACK       = 0x00000100;
112     static final int REFLOW       = 0x00000200;
113     static final int RESIZE       = 0x00000400;
114     static final int RECONSTRAIN  = 0x00000800;
115     static final int ALIGN_TOP    = 0x00001000;
116     static final int ALIGN_BOTTOM = 0x00002000;
117     static final int ALIGN_LEFT   = 0x00004000;
118     static final int ALIGN_RIGHT  = 0x00008000;
119     static final int ALIGNS       = 0x0000f000;
120     static final int CURSOR       = 0x00010000;  // if true, this box has a cursor in the cursor hash; FEATURE: GC issues?
121     static final int CLIP         = 0x00020000;
122     static final int STOP_UPWARD_PROPAGATION    = 0x00040000;
123
124
125     // Instance Data //////////////////////////////////////////////////////////////////////
126
127     Box parent = null;
128     Box redirect = this;
129     int flags = VISIBLE | PACKED | REPACK | REFLOW | RESIZE | FIXED /* ROWS */ | STOP_UPWARD_PROPAGATION | CLIP;
130
131     private String text = null;
132     private Font font = DEFAULT_FONT; 
133     private Picture texture = null;
134     private short strokewidth = 1;
135     public int fillcolor = 0x00000000;
136     private int strokecolor = 0xFF000000;
137
138     private int aspect = 0;
139
140     // specified directly by user
141     public LENGTH minwidth = 0;
142     public LENGTH maxwidth = MAX_LENGTH;
143     public LENGTH minheight = 0;
144     public LENGTH maxheight = MAX_LENGTH;
145     private short rows = 1;
146     private short cols = 0;
147     private short rowspan = 1;
148     private short colspan = 1;
149
150     // computed during reflow
151     private short row = 0;
152     private short col = 0;
153     public LENGTH x = 0;
154     public LENGTH y = 0;
155     public LENGTH ax = 0;   // FEATURE: roll these into x/y; requires lots of changes
156     public LENGTH ay = 0;   // FEATURE: roll these into x/y; requires lots of changes; perhaps y()?
157     public LENGTH width = 0;
158     public LENGTH height = 0;
159     private LENGTH contentwidth = 0;      // == max(minwidth, textwidth, sum(child.contentwidth))
160     private LENGTH contentheight = 0;
161
162     /*
163     private VectorGraphics.VectorPath path = null;
164     private VectorGraphics.Affine transform = null;
165     private VectorGraphics.RasterPath rpath = null;
166     private VectorGraphics.Affine rtransform = null;
167     */
168
169     // Instance Methods /////////////////////////////////////////////////////////////////////
170
171     public final int fontSize() { return font == null ? DEFAULT_FONT.pointsize : font.pointsize; }
172
173     /** invoked when a resource needed to render ourselves finishes loading */
174     public void perform() throws JSExn {
175
176         // FIXME; we can't assume that just because we were performed the image is loaded.
177         // as external events have occured, check the state of box
178         if (texture != null) {
179             if (texture.isLoaded) { minwidth = min(texture.width, maxwidth); minheight = min(texture.height, maxheight); }
180             else { JS res = texture.stream; texture = null; throw new JSExn("image not found: "+res.unclone()); }
181         } else {
182             Log.warn(Box.class, "perform() called with null texture");
183         }
184         MARK_REPACK;
185         MARK_REFLOW;
186         MARK_RESIZE;
187         dirty();
188     }
189
190     public Box getRoot() { return parent == null ? this : parent.getRoot(); }
191     public Surface getSurface() { return Surface.fromBox(getRoot()); }
192
193     // FEATURE: use cx2/cy2 format
194     /** Adds the intersection of (x,y,w,h) and the node's current actual geometry to the Surface's dirty list */
195     public void dirty() { dirty(0, 0, width, height); }
196     public void dirty(int x, int y, int w, int h) {
197         for(Box cur = this; cur != null; cur = cur.parent) {
198             // x and y have a different meaning on the root box
199             if (cur.parent != null && cur.test(CLIP)) {
200                 w = min(x + w, cur.width) - max(x, 0);
201                 h = min(y + h, cur.height) - max(y, 0);
202                 x = max(x, 0);
203                 y = max(y, 0);
204             }
205             if (w <= 0 || h <= 0) return;
206             if (cur.parent == null && cur.getSurface() != null) cur.getSurface().dirty(x, y, w, h);
207             x += cur.x;
208             y += cur.y;
209         }
210     }
211
212
213     // Reflow ////////////////////////////////////////////////////////////////////////////////////////
214
215     // static stuff so we don't have to keep reallocating
216     private static int[] numRowsInCol = new int[65535];
217     private static LENGTH[] colWidth = new LENGTH[65535];
218     private static LENGTH[] colMaxWidth = new LENGTH[65535];
219     private static LENGTH[] rowHeight = new LENGTH[65535];
220     private static LENGTH[] rowMaxHeight = new LENGTH[65535];
221     static { for(int i=0; i<rowMaxHeight.length; i++) { rowMaxHeight[i] = 0; colMaxWidth[i] = 0; } }
222
223     Box nextPackedSibling() { Box b = nextSibling(); return b == null || (b.test(PACKED | VISIBLE)) ? b : b.nextPackedSibling(); }
224     Box firstPackedChild() { Box b = getChild(0); return b == null || (b.test(PACKED | VISIBLE)) ? b : b.nextPackedSibling(); }
225
226     /** pack the boxes into rows and columns; also computes contentwidth */
227     void repack() {
228         for(Box child = getChild(0); child != null; child = child.nextSibling()) child.repack();
229
230         //#repeat COLS/ROWS rows/cols cols/rows col/row row/col colspan/rowspan rowspan/colspan 
231         if (test(FIXED) == COLS) {
232             short r = 0;
233             for(Box child = firstPackedChild(); child != null; r++) {
234                 for(short c=0, numclear=0; child != null && c < cols; c++) {
235                     if (numRowsInCol[c] > r) { numclear = 0; continue; }
236                     if (c != 0 && c + min(cols, child.colspan) - numclear > cols) break;
237                     if (++numclear < min(cols, child.colspan)) continue;
238                     for(int i=c - numclear + 1; i <= c; i++) numRowsInCol[i] += child.rowspan;
239                     child.col = (short)(c - numclear + 1); child.row = r;
240                     rows = (short)max(rows, child.row + child.rowspan);
241                     child = child.nextPackedSibling();
242                     numclear = 0;
243                 }
244             }
245             for(int i=0; i<cols; i++) numRowsInCol[i] = 0;
246         }
247         //#end
248
249         //#repeat contentwidth/contentheight colWidth/rowHeight colspan/rowspan col/row cols/rows minwidth/minheight \
250         //        textwidth/textheight maxwidth/maxheight
251         contentwidth = 0;
252         for(Box child = firstPackedChild(); child != null; child = child.nextPackedSibling())
253             colWidth[child.col] = max(colWidth[child.col], child.contentwidth / child.colspan);
254         for(int i=0; i<cols; i++) { contentwidth += colWidth[i]; colWidth[i] = 0; }
255         contentwidth = bound(minwidth, max(font == null || text == null ? 0 : font.textwidth(text), contentwidth), maxwidth);
256         //#end               
257     }
258     
259     void resize(LENGTH x, LENGTH y, LENGTH width, LENGTH height) {
260         if (x != this.x || y != this.y || width != this.width || height != this.height) {
261             boolean sizechange = (this.width != width || this.height != height) && getTrap("SizeChange") != null;
262             boolean poschange = (this.x != x || this.y != y) && getTrap("PosChange") != null;
263             //do {
264                 int thisx = parent == null ? 0 : this.x;
265                 int thisy = parent == null ? 0 : this.y;
266
267                 // we can't reenable this until we track
268                 // surface-relative sizes; imagine the case of a clear
269                 // surface with nonclear children
270
271                 /*
272                 if (texture == null && (text == null || text.equals(""))) {
273                     if ((fillcolor & 0xff000000) == 0) break;
274                     // FEATURE: more optimizations here
275                     if (this.x == x && this.y == y) {
276                         Box who = (parent == null ? this : parent);
277                         who.dirty(thisx+min(this.width,width), thisy, Math.abs(width-this.width), max(this.height, height));
278                         who.dirty(thisx, thisy+min(this.height,height), min(this.width, width), Math.abs(height-this.height));
279                         break;
280                     }
281                 }
282                 */
283                 (parent == null ? this : parent).dirty(thisx, thisy, this.width, this.height);
284                 this.width = width; this.height = height; this.x = x; this.y = y;
285                 dirty();
286                 //} while (false);
287                 //this.width = width; this.height = height; this.x = x; this.y = y;
288             if (sizechange) putAndTriggerTrapsAndCatchExceptions("SizeChange", T);
289             if (poschange)  putAndTriggerTrapsAndCatchExceptions("PosChange", T);
290         }
291     }
292
293     void resize_children() {
294
295         //#repeat col/row colspan/rowspan contentwidth/contentheight x/y width/height colMaxWidth/rowMaxHeight colWidth/rowHeight \
296         //        HSHRINK/VSHRINK maxwidth/maxheight cols/rows minwidth/minheight colWidth/rowHeight x_slack/y_slack
297         // PHASE 1: compute column min/max sizes
298         for(Box child = firstPackedChild(); child != null; child = child.nextPackedSibling())
299             for(int i=child.col; i < child.col + child.colspan; i++) {
300                 colWidth[i] = max(colWidth[i], child.contentwidth / child.colspan);
301                 colMaxWidth[i] = max(colMaxWidth[i], (child.test(HSHRINK) ? child.contentwidth : child.maxwidth) / child.colspan);
302             }
303         
304         // PHASE 2: hand out slack
305         int x_slack = width;
306         for(int i=0; i<cols; i++) x_slack -= colWidth[i]; 
307         // loop through until there are no more eligible children or all slack is handed out
308         for(int eligible = cols, slacklevel = 0; x_slack > 0 && eligible > 0;) {
309             int increment = max(1, x_slack / eligible);
310             eligible = 0;
311             for(short col=0, count=0; col < cols; col++) {
312                 if (colMaxWidth[col] <= colWidth[col]) continue;
313                 if (slacklevel + increment < colWidth[col]) { eligible++; continue; }
314                 int diff = min(increment, min(colMaxWidth[col] - colWidth[col], slacklevel + increment - colWidth[col]));
315                 eligible++;
316                 colWidth[col] += diff;
317                 x_slack -= diff;
318             }
319             slacklevel += increment;
320         }
321         //#end
322
323         // PHASE 3: assign childrens' actual sizes
324         for(Box child = getChild(0); child != null; child = child.nextSibling()) {
325             if (!child.test(VISIBLE)) continue;
326             int child_width, child_height, child_x, child_y;
327             if (!child.test(PACKED)) {
328                 child_width = child.test(HSHRINK) ? child.contentwidth : min(child.maxwidth, width - Math.abs(child.ax));
329                 child_height = child.test(VSHRINK) ? child.contentheight : min(child.maxheight, height - Math.abs(child.ay));
330                 child_width = max(child.minwidth, child_width);
331                 child_height = max(child.minheight, child_height);
332                 int gap_x = width - child_width;
333                 int gap_y = height - child_height;
334                 child_x = child.ax + (child.test(ALIGN_RIGHT) ? gap_x : !child.test(ALIGN_LEFT) ? gap_x / 2 : 0);
335                 child_y = child.ay + (child.test(ALIGN_BOTTOM) ? gap_y : !child.test(ALIGN_TOP) ? gap_y / 2 : 0);
336             } else {
337                 int unbounded;
338                 //#repeat col/row colspan/rowspan contentwidth/contentheight width/height colMaxWidth/rowMaxHeight \
339                 //        child_x/child_y x/y HSHRINK/VSHRINK maxwidth/maxheight cols/rows minwidth/minheight x_slack/y_slack \
340                 //        colWidth/rowHeight child_width/child_height ALIGN_RIGHT/ALIGN_BOTTOM ALIGN_LEFT/ALIGN_TOP
341                 unbounded = 0;
342                 for(int i = child.col; i < child.col + child.colspan; i++) unbounded += colWidth[i];
343                 child_width = min(unbounded, child.test(HSHRINK) ? child.contentwidth : child.maxwidth);
344                 child_x = test(ALIGN_RIGHT) ? x_slack : test(ALIGN_LEFT) ? 0 : x_slack / 2;
345                 for(int i=0; i < child.col; i++) child_x += colWidth[i];
346                 if (child_width > unbounded) child_x -= (child_width - unbounded) / 2;
347                 //#end
348             }
349             child.resize(child_x, child_y, child_width, child_height);
350         }
351
352         // cleanup
353         for(int i=0; i<cols; i++) { colWidth[i] = 0; colMaxWidth[i] = 0; }
354         for(int i=0; i<rows; i++) { rowHeight[i] = 0; rowMaxHeight[i] = 0; }
355
356         for(Box child = getChild(0); child != null; child = child.nextSibling())
357             if (test(VISIBLE))
358                 child.resize_children();
359     }
360
361
362
363     // Rendering Pipeline /////////////////////////////////////////////////////////////////////
364
365     /** Renders self and children within the specified region. All rendering operations are clipped to xIn,yIn,wIn,hIn */
366     void render(int parentx, int parenty, int cx1, int cy1, int cx2, int cy2, PixelBuffer buf, VectorGraphics.Affine a) {
367         if (!test(VISIBLE)) return;
368         int globalx = parentx + (parent == null ? 0 : x);
369         int globaly = parenty + (parent == null ? 0 : y);
370
371         // intersect the x,y,w,h rendering window with ourselves; quit if it's empty
372         if (test(CLIP)) {
373             cx1 = max(cx1, globalx);
374             cy1 = max(cy1, globaly);
375             cx2 = min(cx2, globalx + width);
376             cy2 = min(cy2, globaly + height);
377             if (cx2 <= cx1 || cy2 <= cy1) return;
378         }
379
380         if ((fillcolor & 0xFF000000) != 0x00000000 || parent == null)
381             buf.fillTrapezoid(cx1, cx2, cy1, cx1, cx2, cy2, (fillcolor & 0xFF000000) == 0 ? 0xffffffff : fillcolor);
382
383         // FIXME: do aspect in here
384         if (texture != null && texture.isLoaded)
385             for(int x = globalx; x < cx2; x += texture.width)
386                 for(int y = globaly; y < cy2; y += texture.height)
387                     buf.drawPicture(texture, x, y, cx1, cy1, cx2, cy2);
388  
389         if (text != null && !text.equals("") && font != null) {
390             int gap_x = width - font.textwidth(text);
391             int gap_y = height - font.textheight(text);
392             int text_x = globalx + (test(ALIGN_RIGHT) ? gap_x : !test(ALIGN_LEFT) ? gap_x/2 : 0);
393             int text_y = globaly + (test(ALIGN_BOTTOM) ? gap_y : !test(ALIGN_TOP) ? gap_y/2 : 0);
394             if (font.rasterizeGlyphs(text, buf, strokecolor, text_x, text_y, cx1, cy1, cx2, cy2, null) == -1)
395                 font.rasterizeGlyphs(text, buf, strokecolor, text_x, text_y, cx1, cy1, cx2, cy2, this);
396         }
397
398         for(Box b = getChild(0); b != null; b = b.nextSibling())
399             b.render(globalx, globaly, cx1, cy1, cx2, cy2, buf, null);
400     }
401     
402     
403     // Methods to implement org.ibex.js.JS //////////////////////////////////////
404
405     public int globalToLocalX(int x) { return parent == null ? x : parent.globalToLocalX(x - this.x); }
406     public int globalToLocalY(int y) { return parent == null ? y : parent.globalToLocalY(y - this.y); }
407     public int localToGlobalX(int x) { return parent == null ? x : parent.globalToLocalX(x + this.x); }
408     public int localToGlobalY(int y) { return parent == null ? y : parent.globalToLocalY(y + this.y); }
409     
410     public Object callMethod(Object method, Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
411         if (nargs != 1 || !"indexof".equals(method)) return super.callMethod(method, a0, a1, a2, rest, nargs);
412         Box b = (Box)a0;
413         if (b.parent != this)
414             return (redirect == null || redirect == this) ?
415                 N(-1) :
416                 redirect.callMethod(method, a0, a1, a2, rest, nargs);
417         return N(b.getIndexInParent());
418     }
419
420     public Enumeration keys() { throw new Error("you cannot apply for..in to a " + this.getClass().getName()); }
421
422     protected boolean isTrappable(Object key, boolean isRead) {
423         if (key == null) return false;
424         else if (key instanceof String) {
425             // not allowed to trap box properties, and no read traps on events
426             String name = (String)key;
427             for (int i=0; i < props.length; i++) if (name.equals(props[i])) return false; 
428             if (isRead) for (int i=0; i < events.length; i++) if (name.equals(events[i])) return false; 
429         }
430
431         return true;
432     }
433
434     public Object get(Object name) throws JSExn {
435         if (name instanceof Number)
436             return redirect == null ? null : redirect == this ? getChild(toInt(name)) : redirect.get(name);
437
438         //#switch(name)
439         case "surface": return parent == null ? null : parent.getAndTriggerTraps("surface");
440         case "indexof": return METHOD;
441         case "text": return text;
442         case "path": throw new JSExn("cannot read from the path property");
443         case "fill": return colorToString(fillcolor);
444         case "strokecolor": return colorToString(strokecolor);
445         case "textcolor": return colorToString(strokecolor);
446         case "font": return font == null ? null : font.stream;
447         case "fontsize": return font == null ? N(10) : N(font.pointsize);
448         case "strokewidth": return N(strokewidth);
449         case "align": return alignToString();
450         case "thisbox": return this;
451         case "shrink": return B(test(HSHRINK) || test(VSHRINK));
452         case "hshrink": return B(test(HSHRINK));
453         case "vshrink": return B(test(VSHRINK));
454         case "aspect": return N(aspect);
455         case "x": return (parent == null || !test(VISIBLE)) ? N(0) : N(x);
456         case "y": return (parent == null || !test(VISIBLE)) ? N(0) : N(y);
457         case "cols": return test(FIXED) == COLS ? N(cols) : N(0);
458         case "rows": return test(FIXED) == ROWS ? N(rows) : N(0);
459         case "colspan": return N(colspan);
460         case "rowspan": return N(rowspan);
461         case "width": return N(width);
462         case "height": return N(height);
463         case "minwidth": return N(minwidth);
464         case "maxwidth": return N(maxwidth);
465         case "minheight": return N(minheight);
466         case "maxheight": return N(maxheight);
467         case "clip": return B(test(CLIP));
468         case "visible": return B(test(VISIBLE) && (parent == null || (parent.get("visible") == T)));
469         case "packed": return B(test(PACKED));
470         case "globalx": return N(localToGlobalX(0));
471         case "globaly": return N(localToGlobalY(0));
472         case "cursor": return test(CURSOR) ? boxToCursor.get(this) : null;
473         case "mouse":
474             if (getSurface() == null) return null;
475             if (getSurface()._mousex == Integer.MAX_VALUE)
476                 throw new JSExn("you cannot read from the box.mouse property in background thread context");
477             return new Mouse();
478         case "numchildren": return redirect == null ? N(0) : redirect == this ? N(treeSize()) : redirect.get("numchildren");
479         case "redirect": return redirect == null ? null : redirect == this ? T : redirect.get("redirect");
480         case "Minimized": if (parent == null && getSurface() != null) return B(getSurface().minimized);
481         default: return super.get(name);
482         //#end
483         throw new Error("unreachable"); // unreachable
484     }
485
486     private class Mouse extends JS.Cloneable {
487         public Object get(Object key) {
488             //#switch(key)
489             case "x": return N(globalToLocalX(getSurface()._mousex));
490             case "y": return N(globalToLocalY(getSurface()._mousey));
491
492             // this might not get recomputed if we change mousex/mousey...
493             case "inside": return B(test(MOUSEINSIDE));
494             //#end
495             return null;
496         }
497     }
498
499     void setMaxWidth(Object value) {
500         do { CHECKSET_INT(maxwidth); MARK_RESIZE; } while(false);
501         if (parent == null && getSurface() != null) getSurface().pendingWidth = maxwidth;
502     }
503     void setMaxHeight(Object value) {
504         do { CHECKSET_INT(maxheight); MARK_RESIZE; } while(false);
505         if (parent == null && getSurface() != null) getSurface().pendingHeight = maxheight;
506     }
507
508     public void put(Object name, Object value) throws JSExn {
509         if (name instanceof Number) { put(toInt(name), value); return; }
510         //#switch(name)
511         case "text": CHECKSET_STRING(text); MARK_RESIZE; dirty();
512         case "strokecolor": value = N(stringToColor((String)value)); CHECKSET_INT(strokecolor); MARK_RESIZE; dirty();
513         case "textcolor": value = N(stringToColor((String)value)); CHECKSET_INT(strokecolor); MARK_RESIZE; dirty();
514         case "text": CHECKSET_STRING(text); MARK_RESIZE; dirty();
515         case "strokewidth": CHECKSET_SHORT(strokewidth); dirty();
516         case "shrink": put("hshrink", value); put("vshrink", value);
517         case "hshrink": CHECKSET_FLAG(HSHRINK); MARK_RESIZE;
518         case "vshrink": CHECKSET_FLAG(VSHRINK); MARK_RESIZE;
519         case "width": put("maxwidth", value); put("minwidth", value); MARK_RESIZE;
520         case "height": put("maxheight", value); put("minheight", value); MARK_RESIZE;
521         case "maxwidth": setMaxWidth(value);
522         case "minwidth": CHECKSET_INT(minwidth); MARK_RESIZE;
523                          if (parent == null && getSurface() != null)
524                              getSurface().setMinimumSize(minwidth, minheight, minwidth != maxwidth || minheight != maxheight);
525         case "maxheight": setMaxHeight(value);
526         case "minheight": CHECKSET_INT(minheight); MARK_RESIZE;
527                          if (parent == null && getSurface() != null)
528                              getSurface().setMinimumSize(minwidth, minheight, minwidth != maxwidth || minheight != maxheight);
529         case "colspan": CHECKSET_SHORT(colspan); MARK_REPACK_parent;
530         case "rowspan": CHECKSET_SHORT(rowspan); MARK_REPACK_parent;
531         case "rows": CHECKSET_SHORT(rows); if (rows==0){set(FIXED, COLS);if(cols==0)cols=1;} else set(FIXED, ROWS); MARK_REPACK;
532         case "cols": CHECKSET_SHORT(cols); if (cols==0){set(FIXED, ROWS);if(rows==0)rows=1;} else set(FIXED, COLS); MARK_REPACK;
533         case "clip": CHECKSET_FLAG(CLIP); if (parent == null) dirty(); else parent.dirty();
534         case "visible": CHECKSET_FLAG(VISIBLE); dirty(); MARK_RESIZE; dirty();
535         case "packed": CHECKSET_FLAG(PACKED); MARK_REPACK_parent;
536         case "aspect": CHECKSET_INT(aspect); dirty();
537         case "globalx": put("x", N(globalToLocalX(toInt(value))));
538         case "globaly": put("y", N(globalToLocalY(toInt(value))));
539         case "align": clear(ALIGNS); setAlign(value == null ? "center" : value); MARK_RESIZE;
540         case "cursor": setCursor(value);
541         case "fill": setFill(value);
542         case "mouse":
543             int mousex = toInt(((JS)value).get("x"));
544             int mousey = toInt(((JS)value).get("y"));
545             getSurface()._mousex = localToGlobalX(mousex);
546             getSurface()._mousey = localToGlobalY(mousey);
547         case "Minimized": if (parent == null && getSurface() != null) getSurface().minimized = toBoolean(value);  // FEATURE
548         case "Maximized": if (parent == null && getSurface() != null) getSurface().maximized = toBoolean(value);  // FEATURE
549         case "Close": if (parent == null && getSurface() != null) getSurface().dispose(true);
550         case "redirect":
551             for(Box cur = (Box)value; cur != null; cur = cur.parent)
552                 if (cur == redirect) {
553                     redirect = (Box)value;
554                     return;
555                 }
556             JS.error("redirect can only be set to a descendant of its current value");
557         case "font":
558             if(!(value instanceof Stream)) throw new JSExn("You can only put streams to the font property");
559             font = value == null ? null : Font.getFont((Stream)value, font == null ? 10 : font.pointsize);
560             MARK_RESIZE;
561             dirty();
562         case "fontsize": font = Font.getFont(font == null ? null : font.stream, toInt(value)); MARK_RESIZE; dirty();
563         case "x": if (parent==null && Surface.fromBox(this)!=null) {
564             CHECKSET_INT(x);
565         } else {
566             if (test(PACKED) && parent != null) return;
567             dirty(); CHECKSET_INT(ax);
568             dirty(); MARK_RESIZE;
569             dirty();
570         }
571         case "y": if (parent==null && Surface.fromBox(this)!=null) {
572             CHECKSET_INT(y);
573         } else {
574             if (test(PACKED) && parent != null) return;
575             dirty(); CHECKSET_INT(ay);
576             dirty(); MARK_RESIZE;
577             dirty();
578         }
579         case "titlebar":
580             if (getSurface() != null && value != null) getSurface().setTitleBarText(JS.toString(value));
581             super.put(name,value);
582             
583         case "Press1":        if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
584         case "Press2":        if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
585         case "Press3":        if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
586         case "Release1":      if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
587         case "Release2":      if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
588         case "Release3":      if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
589         case "Click1":        if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
590         case "Click2":        if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
591         case "Click3":        if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
592         case "DoubleClick1":  if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
593         case "DoubleClick2":  if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
594         case "DoubleClick3":  if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
595         case "KeyPressed":    if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
596         case "KeyReleased":   if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
597         case "Move":          if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
598
599         case "HScroll":       if (!test(STOP_UPWARD_PROPAGATION) && parent != null)
600             parent.putAndTriggerTraps(name, N(((Number)value).floatValue() * ((float)parent.fontSize()) / ((float)fontSize())));
601         case "VScroll":       if (!test(STOP_UPWARD_PROPAGATION) && parent != null)
602             parent.putAndTriggerTraps(name, N(((Number)value).floatValue() * ((float)parent.fontSize()) / ((float)fontSize())));
603
604         case "_Move":         propagateDownward(name, value, false);
605         case "_Press1":       propagateDownward(name, value, false);
606         case "_Press2":       propagateDownward(name, value, false);
607         case "_Press3":       propagateDownward(name, value, false);
608         case "_Release1":     propagateDownward(name, value, false);
609         case "_Release2":     propagateDownward(name, value, false);
610         case "_Release3":     propagateDownward(name, value, false);
611         case "_Click1":       propagateDownward(name, value, false);
612         case "_Click2":       propagateDownward(name, value, false);
613         case "_Click3":       propagateDownward(name, value, false);
614         case "_DoubleClick1": propagateDownward(name, value, false);
615         case "_DoubleClick2": propagateDownward(name, value, false);
616         case "_DoubleClick3": propagateDownward(name, value, false);
617         case "_KeyPressed":   propagateDownward(name, value, false);
618         case "_KeyReleased":  propagateDownward(name, value, false);
619         case "_HScroll":      propagateDownward(name, value, false);
620         case "_VScroll":      propagateDownward(name, value, false);
621
622         case "PosChange":     return;
623         case "SizeChange":    return;
624         case "childadded":    return;
625         case "childremoved":  return;
626         case "Enter":         return;
627         case "Leave":         return;
628
629         case "thisbox":       if (value == null) removeSelf();
630
631         default:              super.put(name, value);
632         //#end
633     }
634
635     private String alignToString() {
636         switch(flags & ALIGNS) {
637             case (ALIGN_TOP | ALIGN_LEFT): return "topleft";
638             case (ALIGN_BOTTOM | ALIGN_LEFT): return "bottomleft";
639             case (ALIGN_TOP | ALIGN_RIGHT): return "topright";
640             case (ALIGN_BOTTOM | ALIGN_RIGHT): return "bottomright";
641             case ALIGN_TOP: return "top";
642             case ALIGN_BOTTOM: return "bottom";
643             case ALIGN_LEFT: return "left";
644             case ALIGN_RIGHT: return "right";
645             case 0: return "center";
646             default: throw new Error("invalid alignment flags: " + (flags & ALIGNS));
647         }
648     }
649
650     private void setAlign(Object value) {
651         //#switch(value)
652         case "center": clear(ALIGNS);
653         case "topleft": set(ALIGN_TOP | ALIGN_LEFT);
654         case "bottomleft": set(ALIGN_BOTTOM | ALIGN_LEFT);
655         case "topright": set(ALIGN_TOP | ALIGN_RIGHT);
656         case "bottomright": set(ALIGN_BOTTOM | ALIGN_RIGHT);
657         case "top": set(ALIGN_TOP);
658         case "bottom": set(ALIGN_BOTTOM);
659         case "left": set(ALIGN_LEFT);
660         case "right": set(ALIGN_RIGHT);
661         default: JS.log("invalid alignment \"" + value + "\"");
662         //#end
663     }
664     
665     private void setCursor(Object value) {
666         if (value == null) { clear(CURSOR); boxToCursor.remove(this); return; }
667         if (value.equals(boxToCursor.get(this))) return;
668         set(CURSOR);
669         boxToCursor.put(this, value);
670         Surface surface = getSurface();
671         if (surface != null) {
672             String tempcursor = surface.cursor;
673             propagateDownward(null, null, false);
674             if (surface.cursor != tempcursor) surface.syncCursor();
675         }
676     }
677
678     private void setFill(Object value) throws JSExn {
679         if (value == null) {
680             // FIXME: Check this... does this make it transparent? 
681             texture = null;
682             fillcolor = 0;
683         } else if (value instanceof String) {
684             // FIXME check double set
685             int newfillcolor = stringToColor((String)value);
686             if (newfillcolor == fillcolor) return;
687             fillcolor = newfillcolor;
688         } else if(value instanceof JS) {
689             texture = Picture.load((JS)value, this);
690         } else {
691             throw new JSExn("fill must be null, a String, or a stream, not a " + value.getClass());
692         }
693         dirty();
694     }
695
696     // FIXME: mouse move/release still needs to propagate to boxen in which the mouse was pressed and is still held down
697     /**
698      *  Handles events which propagate down the box tree.  If obscured
699      *  is set, then we merely check for Enter/Leave.
700      */
701     private void propagateDownward(Object name_, Object value, boolean obscured) {
702
703         String name = (String)name_;
704         if (getSurface() == null) return;
705         int x = globalToLocalX(getSurface()._mousex);
706         int y = globalToLocalY(getSurface()._mousey);
707         boolean wasinside = test(MOUSEINSIDE);
708         boolean isinside = test(VISIBLE) && inside(x, y) && !obscured;
709         if (!wasinside && isinside) {
710             set(MOUSEINSIDE);
711             putAndTriggerTrapsAndCatchExceptions("Enter", T);
712         }
713         if (isinside && test(CURSOR)) getSurface().cursor = (String)boxToCursor.get(this);
714         if (wasinside && !isinside) {
715             clear(MOUSEINSIDE);
716             putAndTriggerTrapsAndCatchExceptions("Leave", T);
717         }
718
719         boolean found = false;
720         if (wasinside || isinside)
721             for(Box child = getChild(treeSize() - 1); child != null; child = child.prevSibling()) {
722                 boolean save_stop = child.test(STOP_UPWARD_PROPAGATION);
723                 Object value2 = value;
724                 if (name.equals("_HScroll") || name.equals("_VScroll"))
725                     value2 = N(((Number)value).floatValue() * ((float)child.fontSize()) / (float)fontSize());
726                 if (obscured || !child.inside(x - child.x, y - child.y)) {
727                     child.propagateDownward(name, value2, true);
728                 } else try {
729                     found = true;
730                     child.clear(STOP_UPWARD_PROPAGATION);
731                     if (name != null) child.putAndTriggerTrapsAndCatchExceptions(name, value2);
732                     else child.propagateDownward(name, value2, obscured);
733                 } finally {
734                     if (save_stop) child.set(STOP_UPWARD_PROPAGATION); else child.clear(STOP_UPWARD_PROPAGATION);
735                 }
736                 if (child.inside(x - child.x, y - child.y))
737                     if (name != null && name.equals("_Move")) obscured = true;
738                     else break;
739             }
740
741         if (!obscured && !found)
742             if ("_Move".equals(name) || wasinside)
743                 if (name != null)
744                     putAndTriggerTrapsAndCatchExceptions(name.substring(1), value);
745     }
746
747     private static int stringToColor(String s) {
748         // FIXME support three-char strings by doubling digits
749         if (s == null) return 0x00000000;
750         else if (SVG.colors.get(s) != null) return 0xFF000000 | toInt(SVG.colors.get(s));
751         else if (s.length() == 7 && s.charAt(0) == '#') try {
752             // FEATURE  alpha
753             return 0xFF000000 |
754                 (Integer.parseInt(s.substring(1, 3), 16) << 16) |
755                 (Integer.parseInt(s.substring(3, 5), 16) << 8) |
756                 Integer.parseInt(s.substring(5, 7), 16);
757         } catch (NumberFormatException e) {
758             Log.info(Box.class, "invalid color " + s);
759             return 0;
760         }
761         else return 0; // FEATURE: error?
762     }
763
764     private static String colorToString(int argb) {
765         if ((argb & 0xFF000000) == 0) return null;
766         String red = Integer.toHexString((argb & 0x00FF0000) >> 16);
767         String green = Integer.toHexString((argb & 0x0000FF00) >> 8);
768         String blue = Integer.toHexString(argb & 0x000000FF);
769         if (red.length() < 2) red = "0" + red;
770         if (blue.length() < 2) blue = "0" + blue;
771         if (green.length() < 2) green = "0" + green;
772         return "#" + red + green + blue;
773     }
774
775     /** figures out what box in this subtree of the Box owns the pixel at x,y relitave to the Surface */
776     public static Box whoIs(Box cur, int x, int y) {
777
778         if (cur.parent != null) throw new Error("whoIs may only be invoked on the root box of a surface");
779         int globalx = 0;
780         int globaly = 0;
781
782         // WARNING: this method is called from the event-queueing thread -- it may run concurrently with
783         // ANY part of Ibex, and is UNSYNCHRONIZED for performance reasons.  BE CAREFUL HERE.
784
785         if (!cur.test(VISIBLE)) return null;
786         if (!cur.inside(x - globalx, y - globaly)) return cur.parent == null ? cur : null;
787         OUTER: while(true) {
788             for(int i=cur.treeSize() - 1; i>=0; i--) {
789                 Box child = cur.getChild(i);
790                 if (child == null) continue;        // since this method is unsynchronized, we have to double-check
791                 globalx += child.x;
792                 globaly += child.y;
793                 if (child.test(VISIBLE) && child.inside(x - globalx, y - globaly)) { cur = child; continue OUTER; }
794                 globalx -= child.x;
795                 globaly -= child.y;
796             }
797             break;
798         }
799         return cur;
800     }
801
802
803     // Trivial Helper Methods (should be inlined) /////////////////////////////////////////
804
805     static short min(short a, short b) { if (a<b) return a; else return b; }
806     static int min(int a, int b) { if (a<b) return a; else return b; }
807     static float min(float a, float b) { if (a<b) return a; else return b; }
808
809     static short max(short a, short b) { if (a>b) return a; else return b; }
810     static int max(int a, int b) { if (a>b) return a; else return b; }
811     static float max(float a, float b) { if (a>b) return a; else return b; }
812
813     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; }
814     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; }
815     static int bound(int a, int b, int c) { if (c < b) return c; if (a > b) return a; return b; }
816     final boolean inside(int x, int y) { return test(VISIBLE) && x >= 0 && y >= 0 && x < width && y < height; }
817
818     void set(int mask) { flags |= mask; }
819     void set(int mask, boolean setclear) { if (setclear) set(mask); else clear(mask); }
820     void clear(int mask) { flags &= ~mask; }
821     boolean test(int mask) { return ((flags & mask) == mask); }
822     
823
824     // Tree Handling //////////////////////////////////////////////////////////////////////
825
826     public final int getIndexInParent() { return parent == null ? 0 : parent.indexNode(this); }
827     public final Box nextSibling() { return parent == null ? null : parent.getChild(parent.indexNode(this) + 1); }
828     public final Box prevSibling() { return parent == null ? null : parent.getChild(parent.indexNode(this) - 1); }
829     public final Box getChild(int i) {
830         if (i < 0) return null;
831         if (i >= treeSize()) return null;
832         return (Box)getNode(i);
833     }
834
835     // Tree Manipulation /////////////////////////////////////////////////////////////////////
836
837     void removeSelf() {
838         if (parent != null) { parent.removeChild(parent.indexNode(this)); return; }
839         Surface surface = Surface.fromBox(this); 
840         if (surface != null) surface.dispose(true);
841     }
842
843     /** remove the i^th child */
844     public void removeChild(int i) {
845         Box b = getChild(i);
846         MARK_REFLOW_b;
847         b.dirty();
848         b.clear(MOUSEINSIDE);
849         deleteNode(i);
850         b.parent = null;
851         MARK_REFLOW;
852         putAndTriggerTrapsAndCatchExceptions("childremoved", b);
853     }
854     
855     public void put(int i, Object value) throws JSExn {
856         if (i < 0) return;
857             
858         if (value != null && !(value instanceof Box)) {
859             if (Log.on) JS.warn("attempt to set a numerical property on a box to a non-box");
860             return;
861         }
862
863         if (redirect == null) {
864             if (value == null) putAndTriggerTrapsAndCatchExceptions("childremoved", getChild(i));
865             else JS.warn("attempt to add/remove children to/from a node with a null redirect");
866
867         } else if (redirect != this) {
868             if (value != null) putAndTriggerTrapsAndCatchExceptions("childadded", value);
869             redirect.put(i, value);
870             if (value == null) {
871                 Box b = (Box)redirect.get(new Integer(i));
872                 if (b != null) putAndTriggerTrapsAndCatchExceptions("childremoved", b);
873             }
874
875         } else if (value == null) {
876             if (i < 0 || i > treeSize()) return;
877             Box b = getChild(i);
878             removeChild(i);
879             putAndTriggerTrapsAndCatchExceptions("childremoved", b);
880
881         } else {
882             Box b = (Box)value;
883
884             // check if box being moved is currently target of a redirect
885             for(Box cur = b.parent; cur != null; cur = cur.parent)
886                 if (cur.redirect == b) {
887                     if (Log.on) JS.warn("attempt to move a box that is the target of a redirect");
888                     return;
889                 }
890
891             // check for recursive ancestor violation
892             for(Box cur = this; cur != null; cur = cur.parent)
893                 if (cur == b) {
894                     if (Log.on) JS.warn("attempt to make a node a parent of its own ancestor");
895                     if (Log.on) Log.info(this, "box == " + this + "  ancestor == " + b);
896                     return;
897                 }
898
899             if (b.parent != null) b.parent.removeChild(b.parent.indexNode(b));
900             insertNode(i, b);
901             b.parent = this;
902             
903             // need both of these in case child was already uncalc'ed
904             MARK_REFLOW_b;
905             MARK_REFLOW;
906             
907             b.dirty(); 
908             putAndTriggerTrapsAndCatchExceptions("childadded", b);
909         }
910     }
911
912     void putAndTriggerTrapsAndCatchExceptions(Object name, Object val) {
913         try {
914             putAndTriggerTraps(name, val);
915         } catch (JSExn e) {
916             JS.log("caught js exception while putting to trap \""+name+"\"");
917             JS.log(e);
918         } catch (Exception e) {
919             JS.log("caught exception while putting to trap \""+name+"\"");
920             JS.log(e);
921         }
922     }
923
924 }
925
926
927
928
929
930
931         /*
932         offset_x = 0;
933         if (path != null) {
934             if (rpath == null) rpath = path.realize(transform == null ? VectorGraphics.Affine.identity() : transform);
935             if ((flags & HSHRINK) != 0) contentwidth = max(contentwidth, rpath.boundingBoxWidth());
936             if ((flags & VSHRINK) != 0) contentheight = max(contentheight, rpath.boundingBoxHeight());
937             // FIXME: separate offset_x needed for the path
938         }
939         // #repeat x1/y1 x2/y2 x3/y3 x4/y4 contentwidth/contentheight left/top right/bottom
940         int x1 = transform == null ? 0 : (int)transform.multiply_px(0, 0);
941         int x2 = transform == null ? 0 : (int)transform.multiply_px(contentwidth, 0);
942         int x3 = transform == null ? contentwidth : (int)transform.multiply_px(contentwidth, contentheight);
943         int x4 = transform == null ? contentwidth : (int)transform.multiply_px(0, contentheight);
944         int left = min(min(x1, x2), min(x3, x4));
945         int right = max(max(x1, x2), max(x3, x4));
946         contentwidth = max(contentwidth, right - left);
947         offset_x = -1 * left;
948         // #end
949         */
950
951
952                     /*
953         if (path != null) {
954             if (rtransform == null) rpath = null;
955             else if (!rtransform.equalsIgnoringTranslation(a)) rpath = null;
956             else {
957                 rpath.translate((int)(a.e - rtransform.e), (int)(a.f - rtransform.f));
958                 rtransform = a.copy();
959             }
960             if (rpath == null) rpath = path.realize((rtransform = a) == null ? VectorGraphics.Affine.identity() : a);
961             if ((strokecolor & 0xff000000) != 0) rpath.stroke(buf, 1, strokecolor);
962             if ((fillcolor & 0xff000000) != 0) rpath.fill(buf, new VectorGraphics.SingleColorPaint(fillcolor));
963         }
964 */
965
966
967 /*
968             VectorGraphics.Affine a2 = VectorGraphics.Affine.translate(b.x, b.y);
969             if (transform != null) a2.multiply(transform);
970             a2.multiply(VectorGraphics.Affine.translate(offset_x, offset_y));
971             a2.multiply(a);
972 */