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