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