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