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