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