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