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