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