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