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