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