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