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