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