2003/08/12 10:03:22
[org.ibex.core.git] / src / org / xwt / Box.java.pp
1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 //     **** This file must be preprocessed before compilation ****
5
6 // RULE: coordinates on non-static methods are ALWAYS relative to the
7 // upper-left hand corner of <tt>this</tt>
8
9 // FIXME: align
10 // FIXME use bitfields
11 // FIXME fixedaspect
12 // FIXME: reflow before allowing js to read from width/height 
13 // FIXME: due to font inheritance, we must dirty and mark all null-font descendents of a node if its font changes
14 // FEATURE: fastpath for rows=1/cols=1
15 // FEATURE: reflow starting with a certain child
16 // FEATURE: separate mark_for_reflow and mark_for_resize
17
18 import java.io.*;
19 import java.net.*;
20 import java.util.*;
21 import org.xwt.js.*;
22 import org.xwt.util.*;
23
24 /**
25  *  <p>
26  *  Encapsulates the data for a single XWT box as well as all layout
27  *  rendering logic.
28  *  </p>
29  *
30  *  <p>
31  *  This is the real meat of XWT. Part of its monolithic design is for
32  *  performance reasons: deep inheritance heirarchies are slow, and
33  *  neither javago nor GCJ can inline across class boundaries.
34  *  </p>
35  *
36  *  <p>The rendering process consists of three phases; each requires
37  *     one DFS pass over the tree</p>
38  *
39  *  <ol><li> <b>repacking</b>: children of a box are packed into columns
40  *           and rows according to their colspan/rowspan attributes and
41  *           ordering.  Minimum and maximum sizes of columns are computed.
42  *
43  *      <li> <b>resizing</b>: width/height and x/y positions of children
44  *           are assigned.  If a PosChange or SizeChange is triggered,
45  *           <tt>Surface.abort</tt> will be set and the resizing process will
46  *           Surface.abort.
47  *
48  *      <li> <b>repainting</b>: children draw their content onto the
49  *           buffer.
50  *  </ol>
51  *
52  *  The first two passes together are called the <i>reflow</i> phase.
53  *
54  *  Reflowing is done in a seperate pass since PosChanges and
55  *  SizeChanges trigger an Surface.abort; if rendering were done in the same
56  *  pass, rendering work done prior to the Surface.abort would be wasted.
57  *
58  *  Repacking is seperate from resizing since a box's size depends on
59  *  both the box's parent's size (so the traversal must be preorder)
60  *  contentwidths of siblings both before and after the box, which in
61  *  turn depend on all descendents of the siblings.  FIXME
62  *
63  *  A note on coordinates: the Box class represents regions
64  *  internally as x,y,w,h tuples, even though the DoubleBuffer class
65  *  uses x1,y1,x2,y2 tuples.
66  */
67 public final class Box extends JS.Scope {
68
69     public Box() { super(null); }
70
71
72     // Misc instance data ////////////////////////////////////////////////////////////////
73
74     private static int sizePosChangesSinceLastRender = 0;
75
76
77     // Misc instance data ////////////////////////////////////////////////////////////////
78
79     boolean needs_reflow = true;         
80     //#define MARK_FOR_REFLOW_this for(Box b2 = this; b2 != null && !b2.needs_reflow; b2 = b2.parent) b2.needs_reflow = true;
81     //#define MARK_FOR_REFLOW_b for(Box b2 = b; b2 != null && !b2.needs_reflow; b2 = b2.parent) b2.needs_reflow = true;
82     //#define MARK_FOR_REFLOW_b_parent for(Box b2 = b.parent; b2 != null && !b2.needs_reflow; b2 = b2.parent) b2.needs_reflow = true;
83
84     private boolean mouseinside = false;
85     Box redirect = this;
86     Surface surface = null;               // null on all non-root boxen
87     Hash traps = null;
88
89
90     // Geometry ////////////////////////////////////////////////////////////////////////////
91
92     // xwt can be compiled with 16-bit lengths to save memory on small devices
93     //#define LENGTH int
94     //#define MAX_LENGTH Integer.MAX_VALUE
95     //#define MIN_LENGTH Integer.MIN_VALUE
96
97     // always correct (set directly by user)
98     LENGTH minwidth = 0;        
99     LENGTH minheight = 0;        
100     LENGTH maxwidth = MAX_LENGTH;
101     LENGTH maxheight = MAX_LENGTH;
102     private LENGTH hpad = 0;
103     private LENGTH vpad = 0;
104     private String text = null;
105     private String font = null;
106     private LENGTH textwidth = 0;
107     private LENGTH textheight = 0;
108
109     // FIXME: use shorts
110     private int rows = 1;
111     private int cols = 0;
112     private int rowspan = 1;
113     private int colspan = 1;
114
115     // computed during reflow
116     LENGTH x = 0;
117     LENGTH y = 0;
118     LENGTH width = 0;
119     LENGTH height = 0;
120     private int row = 0;  // FIXME short
121     private int col = 0;  // FIXME short
122     private LENGTH contentwidth = 0;             // == max(minwidth, textwidth, sum(child.contentwidth) + pad)
123     private LENGTH contentheight = 0;
124
125
126     // Rendering Properties ///////////////////////////////////////////////////////////
127
128     //private SVG.VP path = null;
129     //private SVG.Paint fill = null;
130     //private SVG.Paint stroke = null;
131
132     private Picture image;                       // will disappear
133     private int fillcolor = 0x00000000;          // will become SVG.Paint
134     private int strokecolor = 0xFF000000;        // will become SVG.Paint
135
136     private String cursor = null;                // the cursor for this box
137
138     //FIXME make private
139     public boolean invisible = false;           // true iff the Box is invisible
140     private boolean absolute = false;            // If true, the box will be positioned absolutely
141     private boolean vshrink = false;             // If true, the box will shrink to the smallest vertical size possible
142     private boolean hshrink = false;             // If true, the box will shrink to the smallest horizontal size possible
143     private boolean tile = false; // FIXME: drop this?
144
145     // Instance Methods /////////////////////////////////////////////////////////////////////
146
147     // FIXME: rethink
148     /** Adds the intersection of (x,y,w,h) and the node's current actual geometry to the Surface's dirty list */
149     public final void dirty() { dirty(0, 0, width, height); }
150     public final void dirty(int x, int y, int w, int h) {
151         for(Box cur = this; cur != null; cur = cur.parent) {
152             w = min(x + w, cur.width) - max(x, 0);
153             h = min(y + h, cur.height) - max(y, 0);
154             x = max(x, 0);
155             y = max(y, 0);
156             if (w <= 0 || h <= 0) return;
157             if (cur.parent == null && cur.surface != null) cur.surface.dirty(x, y, w, h);
158             x += cur.x;
159             y += cur.y;
160         }
161     }
162
163     /**
164      *  Given an old and new mouse position, this will update <tt>mouseinside</tt> and check
165      *  to see if this node requires any Enter, Leave, or Move notifications.
166      *
167      *  @param forceleave set to true by the box's parent if the mouse is inside an older
168      *                    sibling, which is covering up this box.
169      */
170     void Move(int oldmousex, int oldmousey, int mousex, int mousey) { Move(oldmousex, oldmousey, mousex, mousey, false); }
171     void Move(int oldmousex, int oldmousey, int mousex, int mousey, boolean forceleave) {
172
173         boolean wasinside = mouseinside;
174         boolean isinside = !invisible && inside(mousex, mousey) && !forceleave;
175         mouseinside = isinside;
176
177         if (!wasinside && !isinside) return;
178
179         if (traps == null) { }
180         else if (!wasinside && isinside && traps.get("Enter") != null) put("Enter", Boolean.TRUE);
181         else if (wasinside && !isinside && traps.get("Leave") != null) put("Leave", Boolean.TRUE);
182         else if (wasinside && isinside && (mousex != oldmousex || mousey != oldmousey) && traps.get("Move") != null) put("Move", Boolean.TRUE);
183
184         if (isinside && cursor != null) getRoot().cursor = cursor;
185
186         // if the mouse has moved into our padding region, it is considered 'outside' all our children
187         if (!(mousex >= hpad && mousey >= vpad && mousex < width - hpad && mousey < height + vpad)) forceleave = true;
188
189         for(Box b = getChild(numChildren() - 1); b != null; b = b.prevSibling()) {
190             b.Move(oldmousex - b.x, oldmousey - b.y, mousex - b.x, mousey - b.y, forceleave);
191             if (b.inside(mousex - b.x, mousey - b.y)) forceleave = true;
192         }
193     }
194
195
196     // Reflow ////////////////////////////////////////////////////////////////////////////////////////
197
198     void reflow() {
199         repack();
200         if (Surface.abort) return;
201         resize(x, y, width, height);
202     }
203
204     /** Checks if the Box's size has changed, dirties it if necessary, and makes sure childrens' sizes are up to date */
205     void repack() {
206         if (!needs_reflow) return;
207         if (numChildren() == 0) { contentwidth = minwidth; contentheight = minheight; return; }
208
209         // --- Phase 0 ----------------------------------------------------------------------
210         // recurse
211         for(Box child = getChild(0); child != null; child = child.nextSibling()) {
212             child.repack();
213             if (Surface.abort) { MARK_FOR_REFLOW_this; return; }
214         }
215
216         // --- Phase 1 ----------------------------------------------------------------------
217         // assign children to their row/column positions (assuming constrained columns)
218         if ((rows == 0 && cols == 0) || (rows != 0 && cols != 0)) throw new Error("rows == " + rows + "   cols == " + cols);
219         //#repeat x/y y/x width/height col/row row/col cols/rows rows/cols colspan/rowspan rowspan/colspan colWidth/rowHeight numRowsInCol/numColsInRow INNER/INNER2 maxwidth/maxheight minwidth/minheight contentwidth/contentheight colMaxWidth/rowMaxHeight OUTER/OUTER2 INNER/INNER2
220         if (rows == 0) {
221             int[] numRowsInCol = new int[cols];           // the number of cells occupied in each column
222             Box child = getChild(0);
223             for(; child != null && (child.absolute || child.invisible); child = child.nextSibling());
224             OUTER: for(int row=0; child != null; row++) {
225                 for(int col=0; child != null && col < cols;) {
226                     INNER: while(true) {  // scan across the row, looking for an unoccupied gap at least as wide as the child
227                         while(col < cols && numRowsInCol[col] > row) col++;
228                         for(int i=col; i < cols && i < col + min(cols, child.colspan); i++)
229                             if (numRowsInCol[col] > row) { col = i + 1; continue INNER; }
230                         break;
231                     }
232                     if (col + min(cols, child.colspan) > cols) break;
233                     for(int i=col; i < col + min(cols, child.colspan); i++) numRowsInCol[i] += child.rowspan;
234                     child.col = col;
235                     child.row = row;
236                     col += min(cols, child.colspan);
237                     child = child.nextSibling();
238                     for(; child != null && (child.absolute || child.invisible); child = child.nextSibling());
239                 }
240             }
241         }
242         //#end
243
244         // --- Phase 2 ----------------------------------------------------------------------
245         // compute the min/max sizes of the columns and rows and set our contentwidth
246         //#repeat x/y y/x width/height col/row cols/rows colspan/rowspan colWidth/rowHeight maxwidth/maxheight minwidth/minheight contentwidth/contentheight colMaxWidth/rowMaxHeight numCols/numRows hpad/vpad
247         contentwidth = 2 * hpad;
248         int numCols = cols;
249         if (numCols == 0)
250             for(Box child = getChild(0); child != null; child = child.nextSibling())
251                 numCols = max(numCols, child.col + child.colspan);
252         LENGTH[] colWidth = new LENGTH[numCols];
253         for(Box child = getChild(0); child != null; child = child.nextSibling())
254             if (!(child.absolute || child.invisible))
255                 colWidth[child.col] = max(colWidth[child.col], child.contentwidth / child.colspan);
256         for(int col=0; col<numCols; col++) contentwidth += colWidth[col];
257         contentwidth = max(textwidth + 2 * hpad, contentwidth);
258         contentwidth = bound(minwidth, contentwidth, maxwidth);
259         //#end
260     }
261
262
263     void resize(LENGTH x, LENGTH y, LENGTH width, LENGTH height) {
264
265         // --- Phase 1 ----------------------------------------------------------------------
266         // run PosChange/SizeChange, dirty as needed
267         if (x != this.x || y != this.y || width != this.width || height != this.height) {
268             (parent == null ? this : parent).dirty(this.x, this.y, this.width, this.height);
269             boolean sizechange = false, poschange = false;
270             if (traps != null && (this.width != width || this.height != height) && traps.get("SizeChange") != null) sizechange = true;
271             if (traps != null && (this.x != x || this.y != y) && traps.get("PosChange") != null) poschange = true;
272             this.width = width; this.height = height; this.x = x; this.y = y;
273             dirty();
274             if (sizechange || poschange)
275                 if (sizePosChangesSinceLastRender == 500) {
276                     if (Log.on) Log.logJS(this, "Warning, more than 500 SizeChange/PosChange traps triggered since last complete render");
277                 } else {
278                     sizePosChangesSinceLastRender++;
279                     if (sizechange) put("SizeChange", Boolean.TRUE);
280                     if (poschange) put("PosChange", Boolean.TRUE);
281                     Surface.abort = true;
282                     return;
283                 }
284             needs_reflow = true;
285         }
286
287         // --- short circuit ----------------------------------------------------------------
288         if (!needs_reflow) return;
289         needs_reflow = false;
290         if (numChildren() == 0) return;
291
292         // --- Phase 2 ----------------------------------------------------------------------
293         // compute the min/max sizes of the columns and rows and set initial width/height to minimums
294
295         //#repeat x/y y/x width/height col/row cols/rows colspan/rowspan colWidth/rowHeight maxwidth/maxheight minwidth/minheight contentwidth/contentheight colMaxWidth/rowMaxHeight marginWidth/marginHeight numCols/numRows
296         int numCols = cols;
297         if (numCols == 0)
298             for(Box child = getChild(0); child != null; child = child.nextSibling())
299                 numCols = max(numCols, child.col + child.colspan);
300         LENGTH[] colWidth = new LENGTH[numCols];
301         LENGTH[] colMaxWidth = new LENGTH[numCols];
302         int marginWidth = width;
303         for(int i=0; i<colMaxWidth.length; i++) colMaxWidth[i] = -1;
304         //#end
305
306         for(Box child = getChild(0); child != null; child = child.nextSibling()) {
307             if (child.absolute || child.invisible) continue;
308             //#repeat x/y y/x width/height col/row cols/rows colspan/rowspan colWidth/rowHeight maxwidth/maxheight minwidth/minheight contentwidth/contentheight colMaxWidth/rowMaxHeight hshrink/vshrink numCols/numRows
309             colWidth[child.col] = max(colWidth[child.col], child.contentwidth / child.colspan);
310             for(int i=child.col; i<child.col+child.colspan && i<numCols; i++)
311                 colMaxWidth[i] = max(colMaxWidth[i], (child.hshrink ? child.contentwidth : child.maxwidth) / child.colspan);
312             //#end
313         }
314
315         //#repeat x/y y/x width/height col/row cols/rows colspan/rowspan colWidth/rowHeight maxwidth/maxheight minwidth/minheight contentwidth/contentheight colMaxWidth/rowMaxHeight marginWidth/marginHeight
316         for(int i=0; i<colMaxWidth.length; i++) if (colMaxWidth[i] == -1) colMaxWidth[i] = MAX_LENGTH;
317
318         for(int i=0; i<colMaxWidth.length; i++) {
319             if (colMaxWidth[i] == MAX_LENGTH) { marginWidth = 0; break; }
320             marginWidth -= colMaxWidth[i];
321             if (marginWidth < 0) { marginWidth = 0; break; }
322         }
323         //#end
324       
325
326         // --- Phase 3 ----------------------------------------------------------------------
327         // hand out the slack
328         int slack;
329         //#repeat x/y y/x width/height col/row cols/rows colspan/rowspan colWidth/rowHeight maxwidth/maxheight minwidth/minheight contentwidth/contentheight colMaxWidth/rowMaxHeight numCols/numRows
330         slack = width;
331         for(int i=0; i<numCols; i++) slack -= colWidth[i];
332         if (numChildren() > 0)
333             while(slack > 0) {  
334                 // FEATURE: inefficient
335                 int startslack = slack;
336                 int increment = max(1, slack / numCols);
337                 for(int col=0; col < numCols && slack > 0; col++) {
338                     slack += colWidth[col];
339                     colWidth[col] = min(colMaxWidth[col], colWidth[col] + increment);
340                     slack -= colWidth[col];
341                 }
342                 if (slack == startslack) break;
343             }   
344         //#end
345
346
347         // --- Phase 4 ----------------------------------------------------------------------
348         // assign children's new sizes and positions and recurse
349         for(Box child = getChild(0); child != null; child = child.nextSibling()) {
350             if (child.invisible) continue;
351             int child_x = 0, child_y = 0, child_width = 0, child_height = 0;
352             if (child.absolute) {
353                 child_x = child.x;
354                 child_y = child.y;
355                 child_width = child.hshrink ? child.contentwidth : min(child.maxwidth, width - child.x - hpad);
356                 child_height = child.vshrink ? child.contentheight : min(child.maxheight, height - child.y - vpad);
357             } else {
358                 int diff;
359                 //#repeat x/y y/x width/height col/row cols/rows colspan/rowspan colWidth/rowHeight maxwidth/maxheight minwidth/minheight contentwidth/contentheight colMaxWidth/rowMaxHeight hshrink/vshrink marginWidth/marginHeight hpad/vpad child_x/child_y child_width/child_height
360                 child_width = 0; for(int i=child.col; i<child.col+child.colspan && i<colWidth.length; i++) child_width += colWidth[i];
361                 diff = bound(child.contentwidth, child_width, child.hshrink ? child.contentwidth : child.maxwidth) - child_width;
362                 child_x = max(hpad, marginWidth / 2); for(int i=0; i<child.col; i++) child_x += colWidth[i];
363                 if (diff < 0) child_x += -1 * (diff / 2);
364                 child_width += diff;
365                 //#end
366             }
367             child.resize(child_x, child_y, child_width, child_height);
368         }
369     }
370
371
372
373
374     // Rendering Pipeline /////////////////////////////////////////////////////////////////////
375
376     /** Renders self and children within the specified region. All rendering operations are clipped to xIn,yIn,wIn,hIn */
377     void render(int parentx, int parenty, int clipx, int clipy, int clipw, int cliph, DoubleBuffer buf) {
378         if (Surface.abort || invisible) return;
379         int globalx = parentx + (parent == null ? 0 : x);
380         int globaly = parenty + (parent == null ? 0 : y);
381
382         // intersect the x,y,w,h rendering window with ourselves; quit if it's empty
383         clipw = min(max(clipx, parent == null ? 0 : globalx) + clipw, (parent == null ? 0 : globalx) + width) - globalx;
384         cliph = min(max(clipy, parent == null ? 0 : globaly) + cliph, (parent == null ? 0 : globaly) + height) - globaly;
385         clipx = max(clipx, parent == null ? 0 : globalx);
386         clipy = max(clipy, parent == null ? 0 : globaly);
387         if (clipw <= 0 || cliph <= 0) return;
388
389         if ((fillcolor & 0xFF000000) != 0x00000000 || parent == null)
390             buf.fillRect(clipx, clipy, clipx + clipw, clipy + cliph, (fillcolor & 0xFF000000) != 0 ? fillcolor : 0xFF777777);
391
392         if (image != null)
393             if (tile) renderTiledImage(globalx, globaly, clipx, clipy, clipw, cliph, buf);
394             else renderStretchedImage(globalx, globaly, clipx, clipy, clipw, cliph, buf);
395
396         //if (text != null && !text.equals("")) renderText(x, y, w, h, buf);
397
398         // now subtract the pad region from the clip region before proceeding
399         clipw = min(max(clipx, globalx + hpad) + clipw, globalx + width - hpad) - clipx;
400         cliph = min(max(clipy, globaly + vpad) + cliph, globaly + height - vpad) - clipy;
401         clipx = max(clipx, globalx + hpad);
402         clipy = max(clipy, globaly + vpad);
403
404         for(Box b = getChild(0); b != null; b = b.nextSibling()) b.render(globalx, globaly, clipx, clipy, clipw, cliph, buf);   
405     }
406
407     void renderStretchedImage(int globalx, int globaly, int x, int y, int w, int h, DoubleBuffer buf) {
408         buf.setClip(x, y, w + x, h + y);
409
410         /*
411         if (fixedaspect) {
412             int hstretch = width / image.getWidth();
413             if (hstretch == 0) hstretch = -1 * image.getWidth() / width;
414             int vstretch = height / image.getHeight();
415             if (vstretch == 0) vstretch = -1 * image.getHeight() / height;
416             if (hstretch < vstretch) height = image.getHeight() * width / image.getWidth();
417             else width = image.getWidth() * height / image.getHeight();
418         }
419         */
420
421         buf.drawPicture(image, globalx, globaly, globalx + width, globaly + height, 0, 0, image.getWidth(), image.getHeight());
422         buf.setClip(0, 0, buf.getWidth(), buf.getHeight());
423     }
424
425     void renderTiledImage(int globalx, int globaly, int x, int y, int w, int h, DoubleBuffer buf) {
426         int iw = image.getWidth();
427         int ih = image.getHeight();
428         // FIXME broken
429         for(int i=(x - x)/iw; i <= (x + w - x)/iw; i++) {
430             for(int j=(y - y)/ih; j<= (y + h - y)/ih; j++) {
431                 
432                 int dx1 = max(i * iw + x, x);
433                 int dy1 = max(j * ih + y, y);
434                 int dx2 = min((i+1) * iw + x, x + w);
435                 int dy2 = min((j+1) * ih + y, y + h);
436                 
437                 int sx1 = dx1 - (i*iw) - x;
438                 int sy1 = dy1 - (j*ih) - y;
439                 int sx2 = dx2 - (i*iw) - x;
440                 int sy2 = dy2 - (j*ih) - y;
441
442                 if (dx2 - dx1 > 0 && dy2 - dy1 > 0 && sx2 - sx1 > 0 && sy2 - sy1 > 0)
443                     buf.drawPicture(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2);
444             }
445         }
446     }
447
448     void renderText(int x, int y, int w, int h, DoubleBuffer buf) {
449         /*
450         if ((textcolor & 0xFF000000) == 0x00000000) return;
451         buf.setClip(x, y, w + x, h + y);
452
453         buf.drawString(font(), text, x + hpad, y + vpad + Platform.getMaxAscent(font()) - 1, textcolor);
454         buf.setClip(0, 0, buf.getWidth(), buf.getHeight());
455         int i=0; while(i<font().length() && !Character.isDigit(font().charAt(i))) i++;
456
457         if (font().lastIndexOf('d') > i) {
458             for(int j = x + hpad; j < x + hpad + textdim(0); j += 2)
459                 buf.fillRect(j, y + vpad + (xwf == null ? Platform.getMaxAscent(font()) : xwf.getMaxAscent()) + 2,
460                              j + 1, y + vpad + (xwf == null ? Platform.getMaxAscent(font()) : xwf.getMaxAscent()) + 2 + 1,
461                              textcolor);
462
463         } else if (font().lastIndexOf('u') > i) {
464             buf.fillRect(x + hpad,
465                         y + vpad + (xwf == null ? Platform.getMaxAscent(font()) : xwf.getMaxAscent()) + 2,
466                         x + hpad + textdim(0),
467                         y + vpad + (xwf == null ? Platform.getMaxAscent(font()) : xwf.getMaxAscent()) + 2 + 1,
468                         textcolor);
469         }
470         */
471     }
472
473
474     // Methods to implement org.xwt.js.JS //////////////////////////////////////
475
476     public Object callMethod(Object method, JS.Array args, boolean checkOnly) throws JS.Exn {
477         if ("indexof".equals(method)) {
478             if (checkOnly) return Boolean.TRUE;
479             if (args.length() != 1 || args.elementAt(0) == null || !(args.elementAt(0) instanceof Box)) return new Integer(-1);
480             Box b = (Box)args.elementAt(0);
481             if (b.parent != Box.this) {
482                 if (redirect == null || redirect == Box.this) return new Integer(-1);
483                 return redirect.callMethod(method, args, checkOnly);
484             }
485             return new Integer(b.getIndexInParent());
486
487         } else if ("apply".equals(method)) {
488             if (checkOnly) return Boolean.TRUE;
489             if (args.elementAt(0) instanceof String) {
490                 String templatename = (String)args.elementAt(0);
491                 Template t = Template.getTemplate(templatename, null);
492                 if (t == null) {
493                     if (Log.on) Log.logJS(this, "template " + templatename + " not found");
494                 } else {
495                     if (ThreadMessage.suspendThread()) try {
496                         JS.Callable callback = args.length() < 2 ? null : (Callable)args.elementAt(1);
497                         t.apply(this, null, null, callback, 0, t.numUnits());
498                     } finally {
499                         ThreadMessage.resumeThread();
500                     }
501                 }
502             } else if (args.elementAt(0) instanceof JS && !(args.elementAt(0) instanceof Box)) {
503                 JS s = (JS)args.elementAt(0);
504                 Object[] keys = s.keys();
505                 for(int j=0; j<keys.length; j++) put(keys[j].toString(), s.get(keys[j]));
506             }
507             return this;
508         }
509         return null;
510     }
511
512     /** Returns the i_th child */
513     public Object get(int i) {
514         if (redirect == null) return null;
515         if (redirect != this) return redirect.get(i);
516         return i >= numChildren() || i < 0 ? null : getChild(i);
517     }
518
519     /**
520      *  Inserts value as child i; calls remove() if necessary.
521      *  This method handles "reinserting" one of your children properly.
522      *  INVARIANT: after completion, getChild(min(i, numChildren())) == newnode
523      *  WARNING: O(n) runtime, unless i == numChildren()
524      */
525     public void put(int i, Object value) {
526         if (i < 0) return;
527
528         if (value != null && !(value instanceof Box)) {
529             if (Log.on) Log.logJS(this, "attempt to set a numerical property on a box to anything other than a box");
530         } else if (redirect == null) {
531             if (Log.on) Log.logJS(this, "attempt to add/remove children to/from a node with a null redirect");
532         } else if (redirect != this) {
533             Box b = value == null ? (Box)redirect.get(i) : (Box)value;
534             redirect.put(i, value);
535             put("0", b);
536         } else if (value == null) {
537             if (i >= 0 && i < numChildren()) {
538                 Box b = getChild(i);
539                 b.remove();
540                 put("0", b);
541             }
542         } else if (value instanceof RootProxy) {
543             if (Log.on) Log.logJS(this, "attempt to reparent a box via its proxy object");
544         } else {
545             Box newnode = (Box)value;
546
547             // check if box being moved is currently target of a redirect
548             for(Box cur = newnode.parent; cur != null; cur = cur.parent)
549                 if (cur.redirect == newnode) {
550                     if (Log.on) Log.logJS(this, "attempt to move a box that is the target of a redirect");
551                     return;
552                 }
553
554             // check for recursive ancestor violation
555             for(Box cur = this; cur != null; cur = cur.parent)
556                 if (cur == newnode) {
557                     if (Log.on) Log.logJS(this, "attempt to make a node a parent of its own ancestor");
558                     if (Log.on) Log.log(this, "box == " + this + "  ancestor == " + newnode);
559                     return;
560                 }
561
562             if (numKids > 15 && children == null) convert_to_array();
563             newnode.remove();
564             newnode.parent = this;
565             
566             if (children == null) {
567                 if (firstKid == null) {
568                     firstKid = newnode;
569                     newnode.prevSibling = newnode;
570                     newnode.nextSibling = newnode;
571                 } else if (i >= numKids) {
572                     newnode.prevSibling = firstKid.prevSibling;
573                     newnode.nextSibling = firstKid;
574                     firstKid.prevSibling.nextSibling = newnode;
575                     firstKid.prevSibling = newnode;
576                 } else {
577                     Box cur = firstKid;
578                     for(int j=0; j<i; j++) cur = cur.nextSibling;
579                     newnode.prevSibling = cur.prevSibling;
580                     newnode.nextSibling = cur;
581                     cur.prevSibling.nextSibling = newnode;
582                     cur.prevSibling = newnode;
583                     if (i == 0) firstKid = newnode;
584                 }
585                 numKids++;
586                 
587             } else {
588                 if (i >= children.size()) {
589                     newnode.indexInParent = children.size();
590                     children.addElement(newnode);
591                 } else {
592                     children.insertElementAt(newnode, i);
593                     for(int j=i; j<children.size(); j++)
594                         getChild(j).indexInParent = j;
595                 }
596             }
597             
598             // need both of these in case child was already uncalc'ed
599             Box b = newnode; 
600             MARK_FOR_REFLOW_b;
601             MARK_FOR_REFLOW_this;
602             
603             newnode.dirty();
604
605             // note that JavaScript box[0] will invoke put(int i), not put(String s)
606             put("0", newnode);
607         }
608     }
609     
610     public Object get(Object name) { return get(name, false); }
611     public Object get(Object name_, boolean ignoretraps) {
612         if (name_ instanceof Number) return get(((Number)name_).intValue());
613
614         if (!(name_ instanceof String)) return null;
615         String name = (String)name_;
616         if (name.equals("")) return null;
617
618         // See if we're reading back the function value of a trap
619         if (name.charAt(0) == '_') {
620             if (name.charAt(1) == '_') name = name.substring(2);
621             else name = name.substring(1);
622             Trap t = Trap.getTrap(this, name);
623             return t == null ? null : t.f;
624         }
625         
626         // See if we're triggering a trap
627         Trap t = traps == null || ignoretraps ? null : (Trap)traps.get(name);
628         if (t != null && t.isreadtrap) return t.perform(Trap.emptyargs);
629
630         // Check for a special handler
631         SpecialBoxProperty gph = (SpecialBoxProperty)SpecialBoxProperty.specialBoxProperties.get(name);
632         if (gph != null) return gph.get(this);
633
634         Object ret = super.get(name);
635         if (name.startsWith("$") && ret == null)
636             if (Log.on) Log.logJS(this, "WARNING: attempt to access " + name + ", but no child with id=\"" + name.substring(1) + "\" found");
637         return ret;
638     }
639
640     public Object[] keys() {
641         Object[] ret = new Object[numChildren()];
642         for(int i=0; i<ret.length; i++) ret[i] = new Integer(i);
643         return ret;
644     }
645
646     /**
647      *  Scriptable.put()
648      *  @param ignoretraps if set, no traps will be triggered (set when 'cascade' reaches the bottom of the trap stack)
649      *  @param rp if this put is being performed via a root proxy, rp is the root proxy.
650      */
651     public void put(Object name, Object value) { put(name, value, false, null); }
652     public void put(Object name, Object value, boolean ignoretraps) { put(name, value, ignoretraps, null); }
653     public void put(Object name_, Object value, boolean ignoretraps, RootProxy rp) {
654         if (name_ instanceof Number) { put(((Number)name_).intValue(), value); return; }
655         if (!(name_ instanceof String)) { super.put(name_,value); return; }
656         String name = name_.toString();
657         if (!ignoretraps && traps != null) {
658             Trap t = (Trap)traps.get(name);
659             if (t != null) {
660                 JS.Array arg = new JS.Array();
661                 arg.addElement(value);
662                 t.perform(arg);
663                 arg.setElementAt(null, 0);
664                 return;
665             }
666         }
667
668         // don't want to really cascade down to the box on this one
669         if (name.equals("0")) return;
670
671         SpecialBoxProperty gph = (SpecialBoxProperty)SpecialBoxProperty.specialBoxProperties.get(name);
672         if (gph != null) { gph.put(name, this, value); return; }
673
674         if (name.charAt(0) == '_') {
675             if (value != null && !(value instanceof JS.Callable)) {
676                 if (Log.on) Log.logJS(this, "attempt to put a non function value (" + value + ") to " + name);
677             } else if (value != null && !(value instanceof JS.CompiledFunction)) {
678                 if (Log.on) Log.logJS(this, "attempt to put a non-compiled function value (" + value + ") to " + name);
679             } else if (name.charAt(1) == '_') {
680                 name = name.substring(2).intern();
681                 Trap t = Trap.getTrap(this, name);
682                 if (t != null) t.delete();
683                 if (value != null) Trap.addTrap(this, name, ((JS.CompiledFunction)value), true, rp);
684             } else {
685                 name = name.substring(1).intern();
686                 Trap t = Trap.getTrap(this, name);
687                 if (t != null) t.delete();
688                 if (value != null) Trap.addTrap(this, name, ((JS.CompiledFunction)value), false, rp);
689             }
690             return;
691         }
692
693         super.put(name, value);
694     }
695
696
697     // Tree Manipulation /////////////////////////////////////////////////////////////////////
698
699     /** The parent of this node */
700     private Box parent = null;
701     
702     // Variables used in Vector mode */
703     /** INVARIANT: if (parent != null) parent.children.elementAt(indexInParent) == this */
704     private int indexInParent;
705     private Vec children = null;
706
707     // Variables used in linked-list mode
708     private int numKids = 0;
709     private Box nextSibling = null;
710     private Box prevSibling = null;
711     private Box firstKid = null;
712     
713     // when we get more than 15 children, we switch to array-mode
714     private void convert_to_array() {
715         children = new Vec(numKids);
716         Box cur = firstKid;
717         do {
718             children.addElement(cur);
719             cur.indexInParent = children.size() - 1;
720             cur = cur.nextSibling;
721         } while (cur != firstKid);
722     }
723     
724     /** remove this node from its parent; INVARIANT: whenever the parent of a node is changed, remove() gets called. */
725     public void remove() {
726         if (parent == null) {
727             if (surface != null) surface.dispose(true);
728             return;
729         }
730         Box oldparent = parent;
731         if (oldparent == null) return;
732         MARK_FOR_REFLOW_this;
733         dirty();
734         mouseinside = false;
735
736         if (parent.children != null) {
737             parent.children.removeElementAt(indexInParent);
738             for(int j=indexInParent; j<parent.children.size(); j++)
739                 (parent.getChild(j)).indexInParent = j;
740
741         } else {
742             if (parent.firstKid == this) {
743                 if (nextSibling == this) parent.firstKid = null;
744                 else parent.firstKid = nextSibling;
745             }
746             parent.numKids--;
747             prevSibling.nextSibling = nextSibling;
748             nextSibling.prevSibling = prevSibling;
749             prevSibling = null;
750             nextSibling = null;
751         }
752         parent = null;
753
754         if (oldparent != null) { Box b = oldparent; MARK_FOR_REFLOW_b; }
755
756         // note that JavaScript box[0] will invoke put(int i), not put(String s)
757         if (oldparent != null) oldparent.put("0", this);
758     }
759
760     /** returns our next sibling (parent[ourindex + 1]) */
761     public final Box nextSibling() {
762         if (parent == null) return null;
763         if (parent.children == null) {
764             if (nextSibling == parent.firstKid) return null;
765             return nextSibling;
766         } else {
767             if (indexInParent >= parent.children.size() - 1) return null;
768             return (Box)parent.children.elementAt(indexInParent + 1);
769         }
770     }
771     
772     /** returns our next sibling (parent[ourindex + 1]) */
773     public final Box prevSibling() {
774         if (parent == null) return null;
775         if (parent.children == null) {
776             if (this == parent.firstKid) return null;
777             return prevSibling;
778         } else {
779             if (indexInParent == 0) return null;
780             return (Box)parent.children.elementAt(indexInParent - 1);
781         }
782     }
783     
784     /** Returns the parent of this node */
785     public Box getParent() { return parent; }
786     
787     /** Returns ith child */
788     public Box getChild(int i) {
789         if (children == null) {
790             if (firstKid == null) return null;
791             if (i >= numKids) return null;
792             if (i == numKids - 1) return firstKid.prevSibling;
793             Box cur = firstKid;
794             for(int j=0; j<i; j++) cur = cur.nextSibling;
795             return cur;
796         } else {
797             if (i >= children.size() || i < 0) return null;
798             return (Box)children.elementAt(i);
799         }
800     }
801     
802     /** Returns the number of children */
803     public int numChildren() {
804         if (children == null) {
805             if (firstKid == null) return 0;
806             int i=1;
807             for(Box cur = firstKid.nextSibling; cur != firstKid; i++) cur = cur.nextSibling;
808             return i;
809         } else {
810             return children.size();
811         }
812     }
813     
814     /** Returns our index in our parent */
815     public int getIndexInParent() {
816         if (parent == null) return 0;
817         if (parent.children == null) {
818             int i = 0;
819             for(Box cur = this; cur != parent.firstKid; i++) cur = cur.prevSibling;
820             return i;
821         } else {
822             return indexInParent;
823         }
824     }
825
826     /** returns the root of the surface that this box belongs to */
827     public final Box getRoot() {
828         if (parent == null && surface != null) return this;
829         if (parent == null) return null;
830         return parent.getRoot();
831     }
832
833
834     // Root Proxy ///////////////////////////////////////////////////////////////////////////////
835
836     // FEATURE: use xwt.graft() here
837     RootProxy myproxy = null;
838     public JS getRootProxy() {
839         if (myproxy == null) myproxy = new RootProxy(this);
840         return myproxy;
841     }
842
843     private static class RootProxy extends JS {
844         Box box;
845         RootProxy(Box b) { this.box = b; }
846         public Object get(Object name) { return box.get(name); }
847         public void put(Object name, Object value) { box.put(name, value, false, this); }
848         public Object[] keys() { return box.keys(); }
849         public Object callMethod(Object method, JS.Array args, boolean justChecking) { return box.callMethod(method,args,justChecking); }
850     }
851
852
853     // Trivial Helper Methods (should be inlined) /////////////////////////////////////////
854
855     static final int min(int a, int b) { if (a<b) return a; else return b; }
856     static final double min(double a, double b) { if (a<b) return a; else return b; }
857     static final int max(int a, int b) { if (a>b) return a; else return b; }
858     static final 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; }
859     static final 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; }
860     static final int bound(int a, int b, int c) { if (c < b) return c; if (a > b) return a; return b; }
861     final boolean inside(int x, int y) { return (!invisible && x >= 0 && y >= 0 && x < width && y < height); }
862     
863     /** figures out what box in this subtree of the Box owns the pixel at x,y relitave to the Surface */
864     public static Box whoIs(Box cur, int x, int y) {
865
866         if (cur.parent != null) throw new Error("whoIs may only be invoked on the root box of a surface");
867         int globalx = 0;
868         int globaly = 0;
869
870         // WARNING: this method is called from the event-queueing
871         // thread -- it may run concurrently with ANY part of XWT, and
872         // is UNSYNCHRONIZED for performance reasons.  BE CAREFUL
873         // HERE.
874
875         if (cur.invisible) return null;
876         if (!cur.inside(x - globalx, y - globaly)) return cur.parent == null ? cur : null;
877         OUTER: while(true) {
878             for(int i=cur.numChildren() - 1; i>=0; i--) {
879                 Box child = cur.getChild(i);
880                 if (child == null) continue;        // since this method is unsynchronized, we have to double-check
881                 globalx += child.x;
882                 globaly += child.y;
883                 if (!child.invisible && child.inside(x - globalx, y - globaly)) { cur = child; continue OUTER; }
884                 globalx -= child.x;
885                 globaly -= child.y;
886             }
887             break;
888         }
889         return cur;
890     }
891
892     /** 
893      *  A helper class for properties of Box which require special
894      *  handling.
895      *
896      *  To avoid excessive use of String.equals(), the Box.get() and
897      *  Box.put() methods employ a Hash keyed on property names that
898      *  require special handling. The value stored in the Hash is an
899      *  instance of an anonymous subclass of SpecialBoxProperty, which knows
900      *  how to handle get()s and put()s for that property name. There
901      *  should be one anonymous subclass of SpecialBoxProperty for each
902      *  specially-handled property on Box.
903      */
904     static class SpecialBoxProperty {
905
906         SpecialBoxProperty() { }
907
908         /** stores instances of SpecialBoxProperty; keyed on property name */
909         static Hash specialBoxProperties = new Hash(200, 3);
910
911         /** this method defines the behavior when the property is get()ed from b */
912         Object get(Box b) { return null; }
913
914         /** this method defines the behavior when the property is put() to b */
915         void put(Box b, Object value) { }
916
917         /** this method defines the behavior when the property is put() to b, allows a single SpecialBoxProperty to serve multiple properties */
918         void put(String name, Box b, Object value) { put(b, value); }
919
920         static {
921             //#repeat fillcolor/strokecolor
922             specialBoxProperties.put("fillcolor", new SpecialBoxProperty() {
923                     public Object get(Box b) {
924                         if ((b.fillcolor & 0xFF000000) == 0) return null;
925                         String red = Integer.toHexString((b.fillcolor & 0x00FF0000) >> 16);
926                         String green = Integer.toHexString((b.fillcolor & 0x0000FF00) >> 8);
927                         String blue = Integer.toHexString(b.fillcolor & 0x000000FF);
928                         if (red.length() < 2) red = "0" + red;
929                         if (blue.length() < 2) blue = "0" + blue;
930                         if (green.length() < 2) green = "0" + green;
931                         return "#" + red + green + blue;
932                     }
933                     public void put(Box b, Object value) {
934                         int newcolor = b.fillcolor;
935                         String s = value == null ? null : value.toString();
936                         if (value == null) newcolor = 0x00000000;
937                         else if (s.length() > 0 && s.charAt(0) == '#')
938                             try {
939                                 newcolor = 0xFF000000 |
940                                     (Integer.parseInt(s.substring(1, 3), 16) << 16) |
941                                     (Integer.parseInt(s.substring(3, 5), 16) << 8) |
942                                     Integer.parseInt(s.substring(5, 7), 16);
943                             } catch (NumberFormatException e) {
944                                 Log.log(this, "invalid color " + s);
945                                 return;
946                             }
947                         else if (SVG.colors.get(s) != null)
948                             newcolor = 0xFF000000 | ((Integer)SVG.colors.get(s)).intValue();
949                         // FIXME put named colors back in
950                         if (newcolor == b.fillcolor) return;
951                         b.fillcolor = newcolor;
952                         b.dirty();
953                     }
954                 });
955             //#end
956         
957             specialBoxProperties.put("color", new SpecialBoxProperty() {
958                     public Object get(Box b) { return b.get("fillcolor"); }
959                     public void put(Box b, Object value) { b.put("fillcolor", value); }
960                 });
961             specialBoxProperties.put("textcolor", new SpecialBoxProperty() {
962                     public Object get(Box b) { return b.get("strokecolor"); }
963                     public void put(Box b, Object value) { b.put("strokecolor", value); }
964                 });
965
966             specialBoxProperties.put("text", new SpecialBoxProperty() {
967                     public Object get(Box b) { return b.text; }
968                     public void put(Box b, Object value) {
969                         String t = value == null ? "null" : value.toString();
970                         if (t.equals(b.text)) return;
971                         // FIXME text is broken
972                     } });
973             specialBoxProperties.put("font", new SpecialBoxProperty() {
974                     public Object get(Box b) { return b.font; }
975                     public void put(Box b, Object value) {
976                         b.font = value == null ? null : value.toString();
977                         //b.fontChanged();
978                         b.dirty();
979                     } });
980         
981             specialBoxProperties.put("thisbox", new SpecialBoxProperty() {
982                     public Object get(Box b) { return b; }
983                     public void put(Box b, Object value) {
984                         if (value == null) b.remove();
985                         else if (value.equals("window") || value.equals("frame")) Platform.createSurface(b, value.equals("frame"), true);
986                         else if (Log.on) Log.log(this, "put invalid value to 'thisbox' property: " + value);
987                     }
988                 });
989
990             specialBoxProperties.put("orient", new SpecialBoxProperty() {
991                     public Object get(Box b) {
992                         if (b.redirect == null) return "horizontal";
993                         else if (b.redirect != b) return get(b.redirect);
994                         else if (b.cols == 1) return "vertical";
995                         else if (b.rows == 1) return "horizontal";
996                         else return "grid";
997                     }
998                     public void put(Box b, Object value) {
999                         if (value == null) return;
1000                         if (b.redirect == null) return;
1001                         if (b.redirect != b) { put(b.redirect, value); return; }
1002                         if (value.equals("vertical")) {
1003                             if (b.rows == 0) return;
1004                             b.rows = 0; b.cols = 1;
1005                         } else if (value.equals("horizontal")) {
1006                             if (b.cols == 0) return;
1007                             b.cols = 0; b.rows = 1;
1008                         } else if (Log.on)
1009                             Log.log(this, "invalid value put to orient property: " + value);
1010                         MARK_FOR_REFLOW_b;
1011                     } });
1012
1013             specialBoxProperties.put("static", new SpecialBoxProperty() {
1014                     public Object get(Box b) {
1015                         String cfsn =
1016                             JS.Thread.fromJavaThread(java.lang.Thread.currentThread()).getCurrentCompiledFunction().getSourceName();
1017                         for(int i=0; i<cfsn.length() - 1; i++)
1018                             if (cfsn.charAt(i) == '.' && (cfsn.charAt(i+1) == '_' || Character.isDigit(cfsn.charAt(i+1)))) {
1019                                 cfsn = cfsn.substring(0, i);
1020                                 break;
1021                             }
1022                         return Static.getStatic(cfsn);
1023                     }
1024                 });
1025
1026             specialBoxProperties.put("shrink", new SpecialBoxProperty() {
1027                     public Object get(Box b) { return (b.vshrink && b.hshrink) ? Boolean.TRUE : Boolean.FALSE; }
1028                     public void put(Box b, Object value) { b.put("hshrink", value); b.put("vshrink", value); }
1029                 });
1030         
1031             //#repeat hshrink/vshrink
1032             specialBoxProperties.put("hshrink", new SpecialBoxProperty() {
1033                     public Object get(Box b) { return new Boolean(b.hshrink); }
1034                     public void put(Box b, Object value) {
1035                         boolean newshrink = stob(value);
1036                         if (b.hshrink == newshrink) return;
1037                         b.hshrink = newshrink;
1038                         MARK_FOR_REFLOW_b;
1039                     }
1040                 });
1041             //#end
1042         
1043             //#repeat x/y
1044             specialBoxProperties.put("x", new SpecialBoxProperty() {
1045                     public Object get(Box b) {
1046                         if (b.surface == null) return new Integer(0);
1047                         if (b.invisible) return new Integer(0);
1048                         return new Integer(b.x);
1049                     }
1050                     public void put(Box b, Object value) {
1051                         if (!b.absolute) return;
1052                         int x = stoi(value);
1053                         if (x == b.x) return;
1054                         b.dirty();
1055                         b.x = x;
1056                         if (b.parent == null && b.surface != null) {
1057                             // FIXME this gets hosed by the #repeat
1058                             //b.surface.setLocation(b.x, b.y);
1059                             b.surface.centerSurfaceOnRender = false;
1060                         }
1061                         MARK_FOR_REFLOW_b;
1062                         b.dirty();
1063                     }
1064                 });
1065             //#end
1066         
1067             //#repeat width/height minwidth/minheight maxwidth/maxheight
1068             specialBoxProperties.put("width", new SpecialBoxProperty() {
1069                     public Object get(Box b) { return new Integer(b.width); }
1070                     public void put(Box b, Object value) {
1071                         b.width = stoi(value);
1072                         if (b.parent == null && b.surface != null) {
1073                             // FIXME this gets hosed...
1074                             //b.surface.setSize(max(Surface.scarPicture.getWidth(), b.width),
1075                             //max(Surface.scarPicture.getHeight(), b.height));
1076                             MARK_FOR_REFLOW_b;
1077                         } else {
1078                             b.minwidth = b.maxwidth = b.width;
1079                             MARK_FOR_REFLOW_b;
1080                         }
1081                     } });
1082             //#end
1083
1084             //#repeat cols/rows rows/cols
1085             specialBoxProperties.put("cols", new SpecialBoxProperty() {
1086                     public Object get(Box b) { return new Double(b.cols); }
1087                     public void put(Box b, Object value) {
1088                         b.cols = stoi(value);
1089                         if (b.cols == 0 && b.rows == 0) b.rows = 1;
1090                         if (b.cols != 0 && b.rows != 0) b.rows = 0;
1091                         MARK_FOR_REFLOW_b;
1092                     } });
1093             //#end
1094         
1095             //#repeat colspan/rowspan
1096             specialBoxProperties.put("colspan", new SpecialBoxProperty() {
1097                     public Object get(Box b) { return new Double(b.colspan); }
1098                     public void put(Box b, Object value) { b.colspan = stoi(value); MARK_FOR_REFLOW_b; }
1099                 });
1100             //#end
1101         
1102             specialBoxProperties.put("tile", new SpecialBoxProperty() {
1103                     public Object get(Box b) { return b.tile ? Boolean.TRUE : Boolean.FALSE; }
1104                     public void put(Box b, Object value) {
1105                         boolean newtile = stob(value);
1106                         if (newtile == b.tile) return;
1107                         b.tile = newtile;
1108                         b.dirty();
1109                     } });
1110         
1111             specialBoxProperties.put("invisible", new SpecialBoxProperty() {
1112                     public Object get(Box b) {
1113                         for (Box cur = b; cur != null; cur = cur.parent) { if (cur.invisible) return Boolean.TRUE; }
1114                         return Boolean.FALSE;
1115                     }
1116                     public void put(Box b, Object value) {
1117                         boolean newinvisible = stob(value);
1118                         if (newinvisible == b.invisible) return;
1119                         b.invisible = newinvisible;
1120                         if (b.parent == null) {
1121                             if (b.surface != null) b.surface.setInvisible(newinvisible);
1122                         } else {
1123                             b.dirty();
1124                             MARK_FOR_REFLOW_b_parent;
1125                             b.parent.dirty(b.x, b.y, b.width, b.height);
1126                         }
1127                     }});
1128         
1129             specialBoxProperties.put("absolute", new SpecialBoxProperty() {
1130                     public Object get(Box b) { return b.absolute ? Boolean.TRUE : Boolean.FALSE; }
1131                     public void put(Box b, Object value) {
1132                         boolean newabsolute = stob(value);
1133                         if (newabsolute == b.absolute) return;
1134                         b.absolute = newabsolute;
1135                         if (b.absolute) { b.x = 0; b.y = 0; }
1136                         if (b.parent != null) MARK_FOR_REFLOW_b_parent;
1137                     } });
1138         
1139             specialBoxProperties.put("image", new SpecialBoxProperty() {
1140                     public Object get(Box b) { return b.image == null ? null : ImageDecoder.imageToNameMap.get(b.image); }
1141                     public void put(Box b, Object value) {
1142                         if ((value == null && b.image == null) ||
1143                             (value != null && b.image != null && value.equals(ImageDecoder.imageToNameMap.get(b.image)))) return;
1144                         String s = value == null ? null : value.toString();
1145                         if (s == null || s.equals("")) b.image = null;
1146                         else {
1147                             if ((b.image = ImageDecoder.getPicture(s)) == null) {
1148                                 if (Log.on) Log.logJS(Box.class, "unable to load image " + s);
1149                             } else {
1150                                 b.minwidth = b.maxwidth = b.image.getWidth();
1151                                 b.minheight = b.maxheight = b.image.getHeight();
1152                                 MARK_FOR_REFLOW_b;
1153                             }
1154                         }
1155                         b.dirty();
1156                     }
1157                 });
1158
1159             //#repeat globalx/globaly x/y
1160             specialBoxProperties.put("globalx", new SpecialBoxProperty() {
1161                     public Object get(Box b) { return new Integer(b.parent == null || b.surface == null ? 0 : b.x); }
1162                     public void put(Box b, Object value) {
1163                         if (b.surface == null || b.parent == null) return;
1164                         b.put("x", new Integer(stoi(value) - stoi(get(b.parent))));
1165                         MARK_FOR_REFLOW_b;
1166                     }
1167                 });
1168             //#end
1169         
1170             specialBoxProperties.put("cursor", new SpecialBoxProperty() {
1171                     public Object get(Box b) { return b.cursor; } 
1172                     public void put(Box b, Object value) {
1173                         b.cursor = (String)value;
1174                         if (b.surface == null) return;
1175
1176                         // see if we need to update the surface cursor
1177                         Surface surface = b.getRoot().surface;
1178                         String tempcursor = surface.cursor;
1179                         b.Move(surface.mousex, surface.mousey, surface.mousex, surface.mousey);
1180                         if (surface.cursor != tempcursor) surface.syncCursor();
1181                     } 
1182                 });
1183         
1184             //#repeat mousex/mousey x/y
1185             specialBoxProperties.put("mousex", new SpecialBoxProperty() {
1186                     public Object get(Box b) {
1187                         Surface surface = b.getRoot().surface;
1188                         if (surface == null) return new Integer(0);
1189                         int mousex = surface.mousex;
1190                         for(Box cur = b; cur != null && cur.parent != null; cur = cur.parent) mousex -= cur.x;
1191                         return new Integer(mousex);
1192                     }
1193                 });
1194             //#end
1195         
1196             specialBoxProperties.put("xwt", new SpecialBoxProperty() {
1197                     public Object get(Box b) { return XWT.singleton; }
1198                 });
1199         
1200             specialBoxProperties.put("mouseinside", new SpecialBoxProperty() {
1201                     public Object get(Box b) { return b.mouseinside ? Boolean.TRUE : Boolean.FALSE; }
1202                 });
1203         
1204             specialBoxProperties.put("numchildren", new SpecialBoxProperty() {
1205                     public Object get(Box b) {
1206                         if (b.redirect == null) return new Integer(0);
1207                         if (b.redirect != b) return get(b.redirect);
1208                         return new Integer(b.numChildren());
1209                     } });
1210         
1211             SpecialBoxProperty mouseEventHandler = new SpecialBoxProperty() {
1212                     public void put(String name, Box b, Object value) {
1213                         Surface surface = b.getRoot().surface;
1214                         if (surface == null) return;
1215                         int mousex = surface.mousex;
1216                         int mousey = surface.mousey;
1217                         for(Box c = b.parent; c != null && c.parent != null; c = c.parent) {
1218                             mousex -= c.x;
1219                             mousey -= c.y;
1220                         }
1221                         for(Box c = b.prevSibling(); c != null; c = c.prevSibling()) {
1222                             if (c.inside(mousex - c.x, mousey - c.y)) {
1223                                 c.put(name, value);
1224                                 return;
1225                             }
1226                         }
1227                         if (b.parent != null) b.parent.put(name, value);
1228                     }};
1229
1230             specialBoxProperties.put("Press1", mouseEventHandler);
1231             specialBoxProperties.put("Press2", mouseEventHandler);
1232             specialBoxProperties.put("Press3", mouseEventHandler);
1233             specialBoxProperties.put("Release1", mouseEventHandler);
1234             specialBoxProperties.put("Release2", mouseEventHandler);
1235             specialBoxProperties.put("Release3", mouseEventHandler);
1236             specialBoxProperties.put("Click1", mouseEventHandler);
1237             specialBoxProperties.put("Click2", mouseEventHandler);
1238             specialBoxProperties.put("Click3", mouseEventHandler);
1239             specialBoxProperties.put("DoubleClick1", mouseEventHandler);
1240             specialBoxProperties.put("DoubleClick2", mouseEventHandler);
1241             specialBoxProperties.put("DoubleClick3", mouseEventHandler);
1242
1243             specialBoxProperties.put("root", new SpecialBoxProperty() {
1244                     public Object get(Box b) {
1245                         if (b.getRoot() == null) return null;
1246                         else if (b.parent == null) return b;
1247                         else return b.getRoot().getRootProxy();
1248                     } });
1249
1250             specialBoxProperties.put("Minimized", new SpecialBoxProperty() {
1251                     public Object get(Box b) {
1252                         if (b.parent == null && b.surface != null) return b.surface.minimized ? Boolean.TRUE : Boolean.FALSE;
1253                         else return null;
1254                     }
1255                     public void put(Box b, Object value) {
1256                         if (b.surface == null) return;
1257                         boolean val = stob(value);
1258                         if (b.parent == null && b.surface.minimized != val) b.surface.setMinimized(val);
1259                     }
1260                 });
1261
1262             specialBoxProperties.put("Maximized", new SpecialBoxProperty() {
1263                     public Object get(Box b) {
1264                         if (b.parent == null && b.surface != null) return b.surface.maximized ? Boolean.TRUE : Boolean.FALSE;
1265                         else return null;
1266                     }
1267                     public void put(Box b, Object value) {
1268                         if (b.surface == null) return;
1269                         boolean val = stob(value);
1270                         if (b.parent == null && b.surface.maximized != val) b.surface.setMaximized(val);
1271                     }
1272                 });
1273
1274             specialBoxProperties.put("toback", new SpecialBoxProperty() {
1275                     public void put(Box b, Object value) {
1276                         if (b.parent == null && stob(value) && b.surface != null) b.surface.toBack();
1277                     }
1278                 });
1279
1280             specialBoxProperties.put("tofront", new SpecialBoxProperty() {
1281                     public void put(Box b, Object value) {
1282                         if (b.parent == null && stob(value) && b.surface != null) b.surface.toFront();
1283                     }
1284                 });
1285
1286             //#repeat hscar/vscar
1287             specialBoxProperties.put("hscar", new SpecialBoxProperty() {
1288                     public void put(Box b, Object value) {
1289                         if (b.parent == null && b.surface != null) {
1290                             b.surface.hscar = stoi(value);
1291                             b.surface.dirty(0, 0, b.surface.width, b.surface.height);
1292                             b.surface.Refresh();
1293                         }
1294                     }
1295                 });
1296             //#end
1297
1298             specialBoxProperties.put("Close", new SpecialBoxProperty() {
1299                     public void put(Box b, Object value) {
1300                         if (b.parent == null && b.surface != null) b.surface.dispose(true);
1301                     }
1302                 });
1303
1304             // these are all do-nothings; just to prevent space from getting taken up in the params Hash.
1305             specialBoxProperties.put("KeyPressed", new SpecialBoxProperty());   // FIXME should cascade
1306             specialBoxProperties.put("KeyReleased", new SpecialBoxProperty());  // FIXME should cascade
1307             specialBoxProperties.put("PosChange", new SpecialBoxProperty());
1308             specialBoxProperties.put("SizeChange", new SpecialBoxProperty());
1309
1310             //#repeat hpad/vpad 
1311             specialBoxProperties.put("hpad", new SpecialBoxProperty() {
1312                     public Object get(Box b) {
1313                         if (b.redirect == null) return new Integer(0);
1314                         if (b.redirect != b) return get(b.redirect);
1315                         return new Integer(b.hpad);
1316                     }
1317                     public void put(Box b, Object value) {
1318                         if (b.redirect == null) return;
1319                         if (b.redirect != b) { put(b.redirect, value); return; }
1320                         int newval = stoi(value);
1321                         if (newval == b.hpad) return;
1322                         b.hpad = newval;
1323                         MARK_FOR_REFLOW_b;
1324                     }
1325                 });
1326             //#end
1327
1328             //#repeat minwidth/minheight maxwidth/maxheight
1329             specialBoxProperties.put("minwidth", new SpecialBoxProperty() {
1330                     public Object get(Box b) { return new Integer(b.minwidth); }
1331                     public void put(Box b, Object value) {
1332                         if (stoi(value) == b.minwidth) return;
1333                         b.minwidth = stoi(value);
1334                         MARK_FOR_REFLOW_b;
1335                     }
1336                 });
1337             specialBoxProperties.put("maxwidth", new SpecialBoxProperty() {
1338                     public Object get(Box b) { return new Integer(b.maxwidth); }
1339                     public void put(Box b, Object value) {
1340                         if (stoi(value) == b.maxwidth) return;
1341                         b.maxwidth = stoi(value);
1342                         MARK_FOR_REFLOW_b;
1343                     }
1344                 });
1345             //#end
1346
1347             specialBoxProperties.put("redirect", new SpecialBoxProperty() {
1348                     public void put(Box b, Object value) { }
1349                     public Object get(Box b) {
1350                         if (b.redirect == null) return null;
1351                         if (b.redirect == b) return Boolean.TRUE;
1352                         return get(b.redirect);
1353                     }
1354                 });
1355
1356             /*
1357             // FIXME: need to be able to read this back
1358             specialBoxProperties.put("titlebar", new SpecialBoxProperty() {
1359                     public void put(Box b, Object value) { surface.setTitleBarText(value.toString()); }
1360                     public Object get(Box b) { return b.ti; }
1361                 });
1362
1363             // FIXME: need to be able to read this back
1364             specialBoxProperties.put("icon", new SpecialBoxProperty() {
1365                     public void put(Box b, Object value) {
1366                         Picture pic = Box.getPicture(value.toString());
1367                         if (pic != null) surface.setIcon(pic);
1368                         else if (Log.on) Log.log(this, "unable to load icon " + value);
1369                     }
1370                     public Object get(Box b) { return b.id; }
1371                 });
1372             */
1373         }
1374
1375         
1376         /** helper that converts a String to a boolean according to JavaScript coercion rules */
1377         public static boolean stob(Object o) {
1378             if (o == null) return false;
1379             return Boolean.TRUE.equals(o) || "true".equals(o);
1380         }
1381
1382         
1383     }
1384         /** helper that converts a String to an int according to JavaScript coercion rules */
1385         public static int stoi(Object o) {
1386             if (o == null) return 0;
1387             if (o instanceof Integer) return ((Integer)o).intValue();
1388
1389             String s;
1390             if (!(o instanceof String)) s = o.toString();
1391             else s = (String)o;
1392
1393             try { return Integer.parseInt(s.indexOf('.') == -1 ? s : s.substring(0, s.indexOf('.'))); }
1394             catch (NumberFormatException e) { return 0; }
1395         }
1396 }
1397         
1398
1399